SwiftLet #02: Let
Let is the keyword to define a variable that can only be set once.
let variable: String
variable = "π"
// variable = "π
" // This will result in a compiler error!
If you uncomment the line where variable
is being set to π
, you will get a compiler error.
Immutable value 'variable' may only be initialized once
NOTE: It says initialized
Example 1 Simply set the value. Go type inference!
let pi = Float.pi
Example 2 What if we tried to modify the value? In this example, we are trying to modify an Array after it has been initialized, in Swift Arrays are Value Types (in a later chapter we will dive into the topic of Value Types and Reference Types).
let variable: [String]
variable = ["π"]
variable.append("π
") // This will also result in a compiler error!
The error you get is because Value Types are always reinitialized! Their value changed, so it is a new value.
Mutating method 'append' may not be used on immutable value 'variable'
Example 3 We can get the variable and use the value, in this example we print the current value to the console.
let variable = "π"
print(variable) // π
Closing Remarks
We learned that let
can only set a variableβs value once! Also we learned that we can get the value of a variable and use it. Finally we learned that Swift has Value Types and Reference Types; also that you can not modify a variable which happens to be a Value Type.