In Swift, what is the difference between let and var, and why do Swift teams declare with let by default?
answer
- one assignment versus many
- the compiler checks every write
- a warning about an unmutated var
- a let may be assigned later, once
basics
~20 slet binds a name to a value exactly once and the compiler rejects any later assignment; var allows reassignment. Teams default to let because it states intent and the compiler warns when a local var is never mutated.
solid answer
~40 s`let` declares a constant: once it has a value, any assignment to it is a compile-time error (`cannot assign to value: 'taxRate' is a 'let' constant`). `var` declares a variable that can be reassigned. Swift code uses `let` unless the value really changes, and the compiler backs the habit up: a local `var` that is never written after its declaration draws the warning `variable 'taxRate' was never mutated; consider changing to 'let' constant`. A local `let` does not need its value on the declaration line: `let fee: Double` can be assigned later, as long as definite initialization proves it is assigned exactly once on every path before it is read. One limit to remember: `let` freezes the binding, so a constant holding a class instance still lets you change that object's `var` properties.
code
swift · 11 linesfunc printReceipt() {
let orderID = "A-1042" // never reassigned: let
var subtotal = 0.0 // grows as lines are added: var
let prices = [4.5, 12.0, 3.25]
for price in prices {
subtotal += price
}
var taxRate = 0.08 // never reassigned, but declared var
print(orderID, subtotal * (1 + taxRate))
}
printReceipt()go deeper
Recall that let is assigned once and var can change, and that writing to a let is a compile-time error. Mention defaulting to let and changing to var only when needed.
Explain the never-mutated warning, why it targets local variables, and how a local let can be assigned later under definite initialization, quoting both errors it can produce.
Show you use the warnings as review signals: a never-mutated var hints at a forgotten update, and a deferred let documents that every branch must decide the value exactly once.
Frame let-by-default as a team convention the compiler already enforces for locals, and know where it stops: globals and stored properties still need reviewers, and let on a class reference freezes only the reference.
## Two kinds of named value Swift has two declarations for a named stored value: - **`let`** introduces a **constant**. After it has been given a value, that value can never be replaced. - **`var`** introduces a **variable**. It can be assigned a new value as often as the code needs. Both are typed at compile time, both can take a type annotation (`let orderID: String = "A-1042"`) or let the compiler infer the type, and both can be declared at global scope, inside a function, or as a property of a type. The core difference between them is whether the name may be **re-assigned**. | | `let` | `var` | |---|---|---| | Can be reassigned | No, compile-time error | Yes | | Value on the declaration line | Optional for a local; required for a global in an ordinary source file | Same rule as `let` | | Compiler nudge | None needed | Warning if a local is never mutated | | Typical use | IDs, configuration, intermediate results | Accumulators, loop state, counters | ## What the compiler enforces The check is entirely **static**: nothing happens at run time, because a program that writes to a `let` never compiles. Assigning to a constant produces: ``` error: cannot assign to value: 'taxRate' is a 'let' constant note: change 'let' to 'var' to make it mutable ``` The same rule covers **function parameters**, which are constants by default: `total = total.rounded()` inside a function whose parameter is `total` fails with the same `is a 'let' constant` error. ## The "never mutated" warning The reverse mistake, a `var` that never changes, is not an error but the compiler notices it. For a **local** variable that is written once at its declaration and only read afterwards, Swift 6.4 reports: ``` warning: variable 'taxRate' was never mutated; consider changing to 'let' constant ``` That warning is a large part of why Swift codebases read as `let`-first. Reviewers treat it as a signal: either the value really is constant and should say so, or the author meant to update it somewhere and forgot. A global `var` or a stored `var` property that nobody writes gets no such warning, because code elsewhere in the module could write it. The compiler has a separate warning for a value that is never **read** at all, `initialization of variable 'unused' was never used; consider replacing with assignment to '_' or removing it`; don't confuse the two. ## Declaring a constant now, assigning it later A local `let` may be declared **without** a value and assigned later. The compiler then runs **definite initialization**: it proves that, on every path, the constant is assigned **exactly once** before anything reads it. 1. Declare the constant with a type annotation, because there is no literal to infer from: `let fee: Double`. 2. Assign it in every branch of an `if`/`else` chain or a `switch`. 3. Read it only after the branches join. If one branch forgets the assignment, the read fails with `constant 'fee' used before being initialized`. If a path assigns twice, for example inside a loop, the compiler reports `immutable value 'fee' may only be initialized once`. The analysis is conservative: when you know a value is always set but the compiler cannot prove it, simplify the branches or fall back to `var`. This deferred form is for locals. A global constant in an ordinary source file must have its value on the declaration line; without one the compiler reports `global 'let' declaration requires an initializer expression`. ## What let does not freeze `let` makes the **binding** constant, not necessarily everything reachable through it. A constant that holds a **class instance** cannot be pointed at a different object, but the object's own `var` properties can still change. A constant that holds a **struct** behaves differently, because a struct is a value. Those rules are covered with value and reference types; for this question it is enough to say that `let` freezes the name's value, whatever kind of value that is. ## Why let by default is the team rule - **Intent**: a reader of a checkout function sees at once which values are fixed (the order ID, the tax rate) and which accumulate (the subtotal). - **Fewer bugs**: an accidental reassignment of a constant is caught at compile time instead of in a code review or a crash report. - **Free tooling**: the never-mutated warning turns the rule into something the compiler checks, so nobody has to police it by hand. - **Easy to relax**: changing `let` to `var` is a one-word edit, and the compiler's note suggests exactly that when you really need mutation.
- Can a local let in Swift be declared without a value, and what does the compiler require?Yes. Write `let fee: Double` with an annotation and assign it later. Definite initialization must prove it is assigned exactly once on every path before the first read; a missing branch gives `constant 'fee' used before being initialized`, and assigning twice, as in a loop, gives `immutable value 'fee' may only be initialized once`. A global constant in a library file has no such option: it needs an initializer expression.
- Does Swift warn about a global var or a stored var property that is never reassigned?No. The `was never mutated` warning targets local variables, whose every use the compiler can see in one function body. A global `var` or a stored `var` property might be written from another file or another type, so the compiler stays silent and the `let` decision is left to the author and the reviewer.
- Why does assigning to a function parameter fail in Swift, and what is the usual fix?Function parameters are constants, so `total = total.rounded()` fails with `cannot assign to value: 'total' is a 'let' constant`. Declare a local instead, often with the same name: `let total = total.rounded()`. Changing the caller's variable is a different feature, an `inout` parameter, covered with function parameters.
- Saying let makes a class instance's properties immutable too
- Believing a let must always get its value on the declaration line
- Treating let as a style hint the compiler never checks
- Thinking a deferred let can be assigned in each loop iteration
- Declaring everything var because the compiler never comments on it