Swift Variables and Constants: How var and let Really Work
In Swift, let declares a constant, a name that receives a value exactly once, and var declares a variable whose value you can replace later. The compiler enforces the difference before the program runs: let score = 10 followed by score = 20 does not build and fails with cannot assign to value: 'score' is a 'let' constant. The recommended default is let, switching to var only when a value must change. The sections below cover the declaration and initialization rules, what let means for structs compared with classes, shadowing, and the compiler errors beginners meet most often.
Difficulty: Beginner
Helpful to know first: How to run a small Swift file, how print() shows values, and the basic types Int, Double and String.
How let and var Bind a Name to a Value
A declaration does two things: it creates a named place that holds a value of one fixed type, and it records whether that place may be assigned again. let says "this name gets one value, ever". var says "this name may be given new values of the same type". Nothing else differs: both can hold any type, both live as long as their scope, and both cost the same at run time.
let maxAttempts = 3
var attemptsLeft = maxAttempts
attemptsLeft -= 1
attemptsLeft -= 1
print("\(attemptsLeft) of \(maxAttempts) attempts left")
// Output: 1 of 3 attempts left1 of 3 attempts left
maxAttempts never changes, so it is a constant. attemptsLeft goes down, so it must be a variable. If you swap the keywords, the program stops compiling at the first -=. That check happens entirely at compile time; there is no run-time "is this constant?" test and no crash to catch.
Two things surprise people coming from other languages. Swift has no const keyword; that is JavaScript. And a Swift let is not a compile-time constant like C++ constexpr: its value can come from a function call or user input, as long as it is assigned only once.
The type comes from the first value or from an annotation
Every constant and variable has one type for its whole life. If you do not write the type, Swift infers it from the initial value: an integer literal gives Int, and a literal with a decimal point gives Double unless you annotate another type.
let count = 10
let pi = 3.14
let ratio: Float = 3.14
print(type(of: count), type(of: pi), type(of: ratio))
// Output: Int Double FloatInt Double Float
A var can change its value but never its type: after var total = 0, assigning 2.5 is an error because total is an Int. How the compiler chooses types is covered in Swift type inference, and the : Type syntax in Swift type annotation.
Declaring and Initializing: Rules the Compiler Checks
Declaring a constant now and assigning it once later
A let does not need its value on the same line. You can declare it with a type and assign it later, as long as every path through the code assigns it exactly once before it is read. This keeps a value constant even when it depends on a condition.
func shippingCost(forOrderTotal total: Double) -> Double {
let cost: Double
if total >= 50 {
cost = 0
} else {
cost = 4.99
}
return cost
}
print(shippingCost(forOrderTotal: 72))
print(shippingCost(forOrderTotal: 20))
// Output:
// 0.0
// 4.990.0 4.99
The compiler follows both branches and proves that cost is set once on each. This is called definite initialization. Assigning it twice gives immutable value 'cost' may only be initialized once; a path that never assigns it gives constant 'cost' used before being initialized.
Declaring several names at once
One var or let can declare several names separated by commas, and a tuple on the right can be split into separate constants. Use _ for a part you do not need.
var x = 0, y = 0
let (width, height) = (1920, 1080)
let (_, statusText) = (404, "Not Found")
x += width / 2
y += height / 2
print(x, y, statusText)
// Output: 960 540 Not Found960 540 Not Found
Destructuring is common with functions that return a tuple, because each part gets a clear name in one line.
Running totals need var, loop values are let
A value that is built up step by step must be a variable. The loop value is different: in for price in prices, Swift creates a fresh constant price for each element.
let prices = [4.5, 12.0, 3.25]
var total = 0.0
for price in prices {
total += price
}
print("Total: \(total)")
// Output: Total: 19.75Total: 19.75
Writing price += 1 inside that loop fails with left side of mutating operator isn't mutable: 'price' is a 'let' constant. The loop value is a copy of the element, so changing it would not change the array anyway (see Find the Bug below).
let with a struct compared with let with a class
This is the rule that confuses people most. For a value type (a struct, an enum, String, Array, Dictionary), let freezes the whole value, including every property and element. For a class instance, let only freezes the reference: the name always points to the same object, but the object's var properties can still change.
struct Point {
var x: Int
var y: Int
}
final class Player {
var score = 0
}
let origin = Point(x: 0, y: 0)
// origin.x = 5 // error: cannot assign to property: 'origin' is a 'let' constant
let player = Player()
player.score += 10 // allowed: the object changes, the reference does not
print(origin.x, player.score)
// player = Player() // error: cannot assign to value: 'player' is a 'let' constant
// Output: 0 100 10
The same rule explains why let names = ["Ana"] followed by names.append("Bo") fails: an array is a value, so a let array cannot grow or shrink. Value semantics compared with reference semantics explains the underlying model.
Shadowing: a new constant with the same name
An inner scope may declare a name that already exists outside it. The inner declaration hides, or shadows, the outer one until the scope ends. The most common use is unwrapping or converting a value under the same name.
let input = "42"
if let input = Int(input) {
print(input + 1) // the Int
}
print(input) // the original String
// Output:
// 43
// 4243 42
Inside the if, input is an Int; after it, the original String is visible again, unchanged. Shadowing never modifies the outer value. It is only allowed in a new scope: declaring the same name twice in one scope fails with invalid redeclaration of 'x'. The shorter if let name { form for optionals is covered in optional binding with if let and guard let.
How let and var Behave in Detail
The compiler tells you when a var could be a let
Inside a function, a var that is never changed produces the warning variable 'name' was never mutated; consider changing to 'let' constant, and a variable that is never read produces initialization of variable 'name' was never used; consider replacing with assignment to '_' or removing it. Treat both as hints to simplify. Top-level code in a script does not get the first warning, so it is easier to leave stray vars there.
A let property stays fixed even inside a var
Mutability is decided at two levels: the instance and each property. A var instance of a struct can change its var properties, but not its let properties. You can still replace the entire value.
struct User {
let id: Int
var name: String
}
var user = User(id: 1, name: "Ana")
user.name = "Ana Lima" // fine: name is a var property
// user.id = 2 // error: cannot assign to property: 'id' is a 'let' constant
user = User(id: 2, name: "Bo") // fine: the whole value is replaced
print(user.id, user.name)
// Output: 2 Bo2 Bo
This is why identifiers are usually let properties: code can update a user's name, but cannot quietly change which user it is.
Some declarations must be var
Computed properties and lazy properties are always declared with var, even when they are read-only. Writing let gives 'let' declarations cannot be computed properties or 'lazy' cannot be used on a let. Here var does not mean "you may assign to it"; it means the value is not stored once at initialization.
Global variables in the Swift 6 language mode
In the Swift 6 language mode, a var declared at global scope in a regular source file is a compile error, because any thread could change it: var 'requestCount' is not concurrency-safe because it is nonisolated global shared mutable state. The compiler suggests making it a let, adding @MainActor, or protecting it yourself. In the default Swift 5 mode the same code compiles. Top-level variables in main.swift or a single-file script are fine in both modes, because that code runs on the main actor. The rules are explained in Sendable, @MainActor and isolation.
Predict the Output
A class instance shared through two constants
Both names are let. What does this print?
final class Counter {
var value = 0
}
let a = Counter()
let b = a
b.value += 5
print(a.value)Show answer
It prints 5. let b = a copies the reference, not the object, so a and b point to the same Counter. let stops you from pointing b at a different object, but changing a var property of the shared object is allowed. If Counter were a struct, b.value += 5 would not even compile.
Copying an array into a constant
What does this print?
var scores = [10, 20]
let snapshot = scores
scores.append(30)
print(snapshot.count, scores.count)Show answer
It prints 2 3. Arrays are values, so let snapshot = scores makes an independent copy (Swift shares the storage until one side changes, then copies). Appending to scores does not affect snapshot, and snapshot itself could never change because it is a let.
Mistakes That Cause let and var Compiler Errors
Assigning a new value to a let constant
The value turned out to change, but the declaration still says let.
Problem: A constant can be assigned only once, so the second line fails with error: cannot assign to value: 'score' is a 'let' constant. This is a compile error, not a crash at run time.
let score = 10
score = 20error: cannot assign to value: 'score' is a 'let' constant
Fix: If the value really changes, declare it with var. If it does not, keep let and remove the assignment, or give the new value its own name.
var score = 10
score = 20
print(score)
// Output: 2020
The corrected version works because var allows the name to be assigned again.
Declaring a name with neither a type nor a value
A declaration that will be filled in later still needs a type.
Problem: Swift cannot infer a type from nothing, so var total on its own fails with error: type annotation missing in pattern.
var total
total = 0.0error: type annotation missing in pattern
Fix: Give an initial value, or write the type and assign before the first read.
var total: Double
total = 0.0
total += 2.5
print(total)
// Output: 2.52.5
This works because the annotation tells Swift the type before the first value arrives.
A branch that forgets to set a constant
Deferred initialization only works when every path assigns the constant.
Problem: When score is below 75, neither branch runs, so grade has no value at return. The compiler refuses it with error: constant 'grade' used before being initialized.
func label(for score: Int) -> String {
let grade: String
if score >= 90 {
grade = "A"
} else if score >= 75 {
grade = "B"
}
return grade
}error: constant 'grade' used before being initialized
Fix: Add the missing path, usually a final else.
func label(for score: Int) -> String {
let grade: String
if score >= 90 {
grade = "A"
} else if score >= 75 {
grade = "B"
} else {
grade = "C"
}
return grade
}
print(label(for: 80), label(for: 60))
// Output: B CB C
Now every path assigns grade exactly once, which is what definite initialization requires.
Calling a mutating method on a let array
People expect let to protect only the name, as with a class, and then try to change the contents.
Problem: An array is a value type, so a let array is completely fixed. append fails with error: cannot use mutating member on immutable value: 'names' is a 'let' constant.
let names = ["Ana"]
names.append("Bo")error: cannot use mutating member on immutable value: 'names' is a 'let' constant
Fix: Use var when the collection changes, or build a new constant from the old one.
var names = ["Ana"]
names.append("Bo")
let moreNames = names + ["Cy"]
print(names, moreNames)
// Output: ["Ana", "Bo"] ["Ana", "Bo", "Cy"]["Ana", "Bo"] ["Ana", "Bo", "Cy"]
Both versions work because the changing collection is a var, and the constant is created whole.
Find the Bug
This code is meant to add 10 to every balance. It compiles without errors or warnings. Why does it print the old balances?
struct Account {
var owner: String
var balance: Double
}
var accounts = [
Account(owner: "Ana", balance: 100),
Account(owner: "Bo", balance: 50),
]
for var account in accounts {
account.balance += 10
}
print(accounts.map(\.balance))Show answer
It prints [100.0, 50.0]. for var account makes each loop value a mutable copy of the element. Account is a struct, so the copy is independent: the loop changes the copy and then throws it away. Writing var here silenced the "not mutable" error but did not make the change reach the array. Loop over the indices and change the array itself:
struct Account {
var owner: String
var balance: Double
}
var accounts = [
Account(owner: "Ana", balance: 100),
Account(owner: "Bo", balance: 50),
]
for index in accounts.indices {
accounts[index].balance += 10
}
print(accounts.map(\.balance))
// Output: [110.0, 60.0][110.0, 60.0]
Choosing Between let, var and the Alternatives
Most values in real code are set once, so let is the default and var is the exception you choose on purpose. Two other declarations cover cases where neither fits well.
| You need | Use | Example |
|---|---|---|
| A value that is set once (most values) | let | let taxRate = 0.2 |
| A value that changes over time | var | var total = 0.0 |
| One value shared by every instance of a type | static let | static let maxUsers = 100 |
| A value recalculated from other values on every read | computed var | var total: Double { price * 2 } |
This page covers how the two keywords work. For the style rule itself, why let-first code is easier to read and review, with refactoring examples, see Swift immutability first.
Interview Questions About let and var
What is the difference between let and var in Swift?
let declares a constant that can be assigned exactly once; var declares a variable that can be reassigned with values of the same type. The compiler enforces it, and for value types let also prevents changing properties or elements.
If a class instance is stored in a let, can you change its properties?
Yes, its var properties. let fixes the reference, so the constant always points to the same object, but the object itself is not frozen. For a struct stored in a let, no property can change.
Can a let constant be declared without a value?
Yes, if it has a type annotation and the compiler can prove it is assigned exactly once before it is read, for example in both branches of an if/else.
Try It Yourself
- Declare constants for the free-shipping threshold (50.0) and the shipping fee (4.99).
- Store the item prices [12.5, 20.25, 9.75] in a constant and add them up in a variable.
- Declare let shipping: Double without a value and assign it in an if/else: free when the subtotal reaches the threshold, the fee otherwise.
- Print the number of items, the subtotal, the shipping and the total.
Expected output: four lines, Items: 3, Subtotal: 42.5, Shipping: 4.99 and Total: 47.49.
Hint: only one value in this program changes after it is first set. Everything else can be a let.
Show solution
let freeShippingThreshold = 50.0
let shippingFee = 4.99
let prices = [12.5, 20.25, 9.75]
var subtotal = 0.0
for price in prices {
subtotal += price
}
let shipping: Double
if subtotal >= freeShippingThreshold {
shipping = 0
} else {
shipping = shippingFee
}
let total = subtotal + shipping
print("Items: \(prices.count)")
print("Subtotal: \(subtotal)")
print("Shipping: \(shipping)")
print("Total: \(total)")
// Output:
// Items: 3
// Subtotal: 42.5
// Shipping: 4.99
// Total: 47.49Items: 3 Subtotal: 42.5 Shipping: 4.99 Total: 47.49
Check Your Understanding
Pick an answer for each question, then check your score.
Summary
- let assigns a name once; var allows reassignment. Swift checks this at compile time, and const does not exist in Swift.
- Prefer let and switch to var only when the value must change.
- A constant can be declared with a type and assigned later, if every path assigns it exactly once before use.
- For structs, arrays and other value types, let freezes the whole value; for class instances it freezes only the reference.
- Shadowing creates a new name in an inner scope and never changes the outer value; redeclaring in the same scope is an error.
- Types are fixed at declaration: let pi = 3.14 is a Double for good.
Next, learn what those values can be and where each type reaches its limits: Swift data types.