Chapter 69: Swift Mutability (let vs var)
1. The Core Idea – What “mutability” really means
In Swift, mutability = “can this thing be changed after I create it?”
Swift gives you two keywords to control mutability:
- let = constant → the value cannot be changed after creation (immutable = “I promise this will never change”)
- var = variable → the value can be changed later (mutable = “this is allowed to change”)
Very important mindset shift (this is what separates beginners from good Swift developers):
In modern Swift, the default recommendation is: Use let by default — everywhere. Use var only when you are sure the value will actually need to change.
This is not just a style rule — it is one of the strongest safety features of Swift.
2. The simplest examples – feel the difference
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// let = constant = cannot be reassigned let name = "Priya" name = "Sneha" // ❌ Compile error: Cannot assign to value: 'name' is a 'let' constant // var = variable = can be reassigned var score = 100 score = 150 // ✅ OK score += 50 // ✅ OK, now 200 score = 0 // ✅ OK |
|
0 1 2 3 4 5 6 7 8 9 10 |
let temperature = 32.5 // temperature = 33.0 // ❌ cannot change var currentTemperature = 32.5 currentTemperature = 33.2 // ✅ OK |
3. The most important rule used by experienced developers
Ask yourself this question every single time you declare something:
“Will this value ever need to be completely replaced with a different value later in this scope?”
- If the answer is “No” or “Probably not” → use let
- If the answer is “Yes, definitely” → use var
This single question catches ~80–90% of cases correctly.
4. Real-life examples – how good developers actually choose let vs var
Example 1 – User profile (very common)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
struct User { let id: UUID // never changes let createdAt: Date // never changes let email: String // usually never changes var displayName: String // user can change it var bio: String? // user can change it var profilePhotoURL: URL? // user can change it var isPremium: Bool // can change over time } |
→ Identity fields → let → Editable fields → var
Example 2 – Settings screen
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
struct AppSettings { let appVersion = "2.3.1" // never changes in this run let apiBaseURL = URL(string: "https://api.example.com/v2")! var theme: Theme = .system // user can change var fontSize: CGFloat = 16 // user can change var notificationsEnabled = true // user can change } |
→ Fixed constants → let → User preferences → var
Example 3 – Game state (very typical)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class GameSession { let playerID: UUID // fixed let startTime: Date // fixed var currentScore = 0 // changes a lot var livesRemaining = 3 // decreases var level = 1 // increases var isGameOver = false // changes once } |
→ Identity & creation data → let → State that changes during gameplay → var
Example 4 – Function parameters & local variables
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
func calculateTotalPrice(items: [CartItem], taxRate: Double) -> Double { let subtotal = items.reduce(0.0) { $0 + $1.price * Double($1.quantity) } // subtotal is never reassigned → let let taxAmount = subtotal * taxRate // final total is never reassigned → let let finalTotal = subtotal + taxAmount return finalTotal } |
Golden habit: Inside functions, default to let for every local variable unless you actually reassign it.
5. Very Common Beginner Mistakes & Correct Habits
| Mistake | Wrong / Risky code | Correct / Better habit | Why? |
|---|---|---|---|
| Using var everywhere “just in case” | var name = “Priya”; var age = 24; | Default to let unless you really reassign | let prevents accidental changes + better safety |
| Reassigning constants by mistake | let maxUsers = 100; maxUsers = 200 | Compiler error — good! | let protects you from bugs |
| Using var for values that never change | var pi = 3.14159 | let pi = 3.14159 | False expectation — looks like it may change |
| Declaring loop counters as let | for let i in 0..<10 { i += 1 } | for i in 0..<10 { … } (implicitly mutable) | Loop variable is mutable by default |
| Making struct properties let when they should be editable | struct User { let name: String } | var name if user can change it | Immutability is good, but not when it blocks real use |
6. Quick Summary – Decision Checklist (use this every time)
When you write:
|
0 1 2 3 4 5 6 |
let/var something = … |
Ask yourself:
- Will I ever need to completely replace this value with a different value later? → Yes → var → No / probably not → let
- Is this value part of the identity or fixed state of the object? → Usually let (id, createdAt, email…)
- Is this value user-editable or changes over time? → Usually var (displayName, score, isPremium…)
- Inside a function — is this a temporary calculation that won’t be reassigned? → Almost always let
7. Small Practice – Choose let or var
For each line, decide let or var and explain why:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
____ maximumUsers = 1000 ____ currentScore = 0 ____ apiKey = "xyz123" ____ temperature = 32.5 ____ playerName = "Aarav" ____ playerName = getNewNameFromServer() ____ isDarkMode = traitCollection.userInterfaceStyle == .dark ____ counter = 0; counter += 1 (in loop) |
Expected answers (and reasoning):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
let maximumUsers = 1000 // fixed limit, never changes var currentScore = 0 // definitely increases let apiKey = "xyz123" // fixed secret var temperature = 32.5 // can change over time let playerName = "Aarav" // fixed at creation var playerName = getNewNameFromServer() // value changes let isDarkMode = traitCollection.userInterfaceStyle == .dark // computed once, not reassigned var counter = 0 // counter must increase |
Paste your decisions here if you want feedback!
What would you like to explore next?
- Mutability inside structs vs classes (very important difference)
- let with computed properties & lazy properties
- When var is actually safer (mutable state in view models…)
- Mutability in SwiftUI (@State vs let, @Binding)
- Or move to another topic (loops, functions, optionals, switch…)
Just tell me — we’ll continue in the same clear, detailed, teacher-like style 😊
