Every time you create a name in Swift, the language makes you answer one question first: will this value ever change? There are two keywords, one for each answer:
letdeclares a constant — the value is set once and can never be reassigned.vardeclares a variable — the value is allowed to change later.
This is not just style. When you write let, the compiler guarantees the value never changes — if any line of your program tries to modify it, the program simply refuses to compile. Whole categories of bugs disappear before the code even runs. That is why Swift programmers reach for let by default and only use var when a value genuinely needs to change — a counter, a running total, a position that moves:
let pi = 3.14159 // fixed forever — perfect for let
var lives = 3 // will go down when the player is hit
lives -= 1 // OK — lives was declared with var
print(lives) // prints 2
In fact, if you declare something with var and never change it, the compiler nudges you the other way with a warning: variable 'lives' was never mutated; consider changing to 'let' constant.
The trap:
Sooner or later you will try to change a constant. The compiler stops you with this exact error — read it carefully, because the note: underneath hands you the fix:
p1.swift:2:1: error: cannot assign to value: 'maxLives' is a 'let' constant
1 | let maxLives = 3
| `- note: change 'let' to 'var' to make it mutable
2 | maxLives = 5
| `- error: cannot assign to value: 'maxLives' is a 'let' constant
The message names the exact constant (maxLives), points at the line that tried to change it, and the note tells you the two honest ways out: keep let and stop reassigning, or switch the declaration to var because the value really does need to change. Compound operators like += hit the same wall — left side of mutating operator isn't mutable: 'maxLives' is a 'let' constant.
Assignment
Follow the Coding Tutorial to build a tiny game setup with one constant and one variable:
- Declare a constant
maxLivesequal to3— the rules of the game never change — and print it. - Declare a variable
scorestarting at0, add10and then5to it with+=, and print the total.
The exact expected output is:
maxLives = 3
score = 15
Hint
Use print("maxLives = \(maxLives)")-style string interpolation: \(...) drops a value into the middle of a string. And if the compiler says cannot assign to value or left side of mutating operator isn't mutable, the name you are changing was declared with let — the one value that must change here is score, so declare it with var.
Free plan: 30 tutor messages. Premium is unlimited.