Camp 1 · Schritt 3 von 12
let and var
Constants first, variables when needed — Swift's core habit, and why Xcode itself nags you about it.
Swift's two declaration keywords draw one line: can this value ever change?
let: constants
let binds a value permanently. Reassignment is a compile error:
"Cannot assign to value: 'altitude' is a 'let' constant" — with a
suggested fix.
var: variables
var allows change — counters, accumulators, anything genuinely mutable.
The Swift habit: let until proven var
Idiomatic Swift declares everything with let first and only
promotes to var when the compiler proves mutation is needed. It's such
core culture that Xcode literally warns: "variable was never mutated;
consider changing to let."
Why care so much?
- A
letis a promise to readers: this won't shift under you - The compiler can optimize constants aggressively
- Accidental mutation — a classic bug source — becomes impossible
The same const-first instinct you met in JavaScript and Dart; Swift just enforces it with the friendliest nagging in the business.
let maxDepth = 30; maxDepth = 40 — what happens?
You declared var total = 0 but never changed it. Idiomatic Swift says…