The question every Swift name answers
When you create a name in Swift, you decide whether its value will ever change. Two keywords express the answer:
letdeclares a constant. The value is set once and can never be reassigned.vardeclares a variable. The value can be reassigned later.
let pi = 3.14159
var lives = 3
lives -= 1
print(lives)
2
Pi never changes, so it is a let. The number of lives goes down when the player is hit, so it is a var. The update lives -= 1 works only because of the var.
Why Swift cares
With let, the compiler guarantees that no line of the program changes the value. Any attempt becomes a compile error, so a whole category of bugs cannot occur. This is why Swift code uses let by default and var only for values that really change, such as counters, running totals and positions.
The habit works in the other direction too. A var that nothing ever changes only tells the reader that it might change, so it should be a let.
The error you will meet
Sooner or later you try to change a constant:
let maxLives = 3
maxLives = 5
error: cannot assign to value: 'maxLives' is a 'let' constant
note: change 'let' to 'var' to make it mutable
The message names the constant and the note offers two ways out: stop reassigning it, or declare it with var because it really must change. Compound operators hit the same wall. For let maxLives = 3, the line maxLives += 1 reports left side of mutating operator isn't mutable: 'maxLives' is a 'let' constant.
The exercise, step by step
The program sets up a tiny game with one constant and one variable, and prints both. The expected output is exactly:
maxLives = 3
score = 15
- Declare the constant.
let maxLives = 3. The rules of the game do not change, soletfits. - Print it with interpolation. Inside a string,
\(maxLives)is replaced by the value. Reading a constant is always allowed. - Declare the variable.
var score = 0. A score is a running total, so it has to be avar. - Add 10 with
score += 10. This line compiles only becausescoreis avar. - Add 5 with
score += 5. Each update starts from whatever the variable holds at that moment, so the score is now 15. - Print the total in the same
label = valueformat.
The solution in Swift
let maxLives = 3
print("maxLives = \(maxLives)")
var score = 0
score += 10
score += 5
print("score = \(score)")
The details worth knowing:
- The type is inferred. Both names are
Int. A new value forscoremust also be anInt. +=is shorthand.score += 10meansscore = score + 10.- Constants and collections. For an array,
letmeans the contents cannot change either. Withlet list = [1, 2], callinglist.append(3)is an error. The same array declared withvarcan grow. - A constant can be assigned once, later.
let later: Intfollowed bylater = 5is allowed, as long as the assignment happens exactly once.
Common mistakes
- Declaring
scorewithlet. The first+=fails to compile. - Declaring
maxLiveswithvarout of habit. It compiles, but nothing stops a later line from changing it. - Switching to
varto silence an error without thinking. The error often points at a real design mistake. - Printing before the updates. The final
printmust come after both+=lines to show 15.
Key takeaways
- Use
letwhen the value is fixed andvarwhen it has to change. - The compiler enforces the choice, so a mistaken change is caught before the program runs.
- Start with
letand switch tovaronly when needed.
