Swift – Constants, Variables & Print function
Constants and variables are those elements in a code linked with a particular type of value such as a number, a character, a string, etc. Constants once declared in a code cannot be changed. In comparison, variables can change at any time in a code within the scope.
Declaring Constants & Variables in Swift:
Constants and variables in Swift must be declared in scope before they are used. In Swift, to declare a constant, we use the “let” keyword and to declare a variable, we use the “var” keyword. Swift does not require you to end a statement with a semicolon (;).
let temp = 15 var count = 0
In general, we can declare a number of constants or variables in a single line separated by commas.
let a = 55, b = 1, c = 15 var p = 6, q = 12, r = 18
Type annotation means explicitly mentioning the type of constant or variable when declared. For example, we declare a string variable, and we haven’t initialized it yet. So, we write:
var stringName : String
Similarly, if it’s an integer, we write:
var numberTemp : Int
As we can declare several constants or variables in a single line separated by commas, if all the items are of the same type, let us say “String”, we then write:
var name, place, city: String
Naming Constants & Variables:
The naming convention may contain any character, excluding mathematical symbols, private-Unicode scalar values, arrows, and whitespace characters.
let ❤️ = “Love” let ❤️❤️ = “more love” var g4g = “GeeksforGeeks”
Printing Constants & Variables:
The function in Swift to print any constant or variable value is print(_:separator:terminator:)
We declare a constant “placeName” and initialize it as a string by linking a value “Mumbai” to it. Now to print our constant, we call the print function as follows:
let placeName = “Mumbai” print(placeName) Output: Mumbai
String interpolation means to include a constant or a variable as a placeholder while printing and prompt Swift to replace the placeholder with the actual value of that constant or variable.
var cityName = “Mumbai” print(“I live in \(cityName)”) Output: I live in Mumbai