In Swift 5.8 we use var
and let for locals. The constant "let" can never be changed. But for loops and objects like arrays, var
is needed.
If our program gives us a "cannot assign to value" error, we should consider changing a let to a var
. This will often fix the compilation issue.
Let us use the var
keyword in a simple example. Here we bind the identifier "color" to the string
"blue." We then bind "color" to green with a reassignment.
var
.// Create a variable and assign a string literal to it. var color = "blue" print(color) // Change the assigned value. color = "green" print(color)blue green
Now we cause some trouble. We create a constant with the value "blue." But then we try to change its binding to point to "green." This fails and a compile-time error is caused.
// This part works. let color = "blue" print(color) // But this part does not compile. // ... A constant cannot be reassigned. color = "green" print(color)Cannot assign to value: 'color' is a 'let' constant
Here we fix our "cannot assign to value" error. We use two "let" constants. This style of code may lead to better, more durable programs.
// For constants, we must use separate bindings. let color1 = "orange" print(color1) let color2 = "mauve" print(color2)orange mauve
A func
cannot modify its arguments in Swift (by default). With the var
keyword, we specify that an argument can be modified by the method's statements.
func incrementId(id var: Int) -> Int { // Print and increment the var argument. print(id) id += 1 print(id) return id } var id = 10 // Call incrementId with argument of 10. // ... Print the returned value. print(incrementId(id: id))10 11 11
Here the incrementId
func
tries to increment its argument Int
. But the argument is not marked with var
, so this causes a "mutating operator" error.
func incrementId(id: Int) { // This causes an error. id += 1 } var id = 55 incrementId(id: id)Cannot pass immutable value to mutating operator: 'id' is a 'let' constant
Typically, the let
-keyword is best when it can be applied. If a variable is mutated in a program, the var
keyword can be used. But immutable things offer advantages and are often preferred.