Constants and Variables associate a name with a value of particular type. They are like containers to store values.They must be declared before they are used.
- Constants are declared using ‘let’ keyword.Values associated with a constant cannot be changed once they are assigned.
- Variables are declared using ‘var’ keyword.Values associated with a variable can be changed after they are assigned.
var textOne = “Hello, playground”
Above statement says: Declare a variable named textOne and assign it with a value of “Hello, Playground”.
let textOne = “Hello, playground”
Above statement says: Declare a constant named textOne and assign it with a value of “Hello, Playground”.
- We can declare multiple constants / variables of same type separated by commas in a single line using let/var only once.
var class10 = 24, class11 = 30, class12 = 25
- Names associated with constants and variables cannot contain whitespace characters, private unicode characters, line-box drawing characters, mathematical symbols and arrows. Names must not begin with numbers but can have them elsewhere in the name.
- We can print the current value of constant and variable using print function. Using string interpolation, the value of constant or variable can be included as a part of string by enclosing them within a parentheses followed by backslash before the opening parentheses.
let counter = 35
print(” The counter value stored inside the constant counter is given by : \(counter)”)