Swift Mutability (let vs var)

Swift Tutorial

🔐 Swift Mutability (let vs var) – Complete Beginner to Interview Guide

In Swift, mutability is controlled using two keywords:

  • let → constant (immutable)

  • var → variable (mutable)

Understanding this difference is fundamental, heavily used in real apps, and frequently asked in interviews.


1️⃣ What is Mutability in Swift? ⭐

Mutability means whether a value can be changed after it is created.

  • Mutable → can change

  • Immutable → cannot change


2️⃣ let – Immutable (Constant) ⭐

Once assigned, a let value cannot be changed.

let age = 25
// age = 30 ❌ Error

📌 Use let by default.


3️⃣ var – Mutable (Variable) ⭐

A var value can be changed.

var score = 50
score = 80 // ✅ Allowed

4️⃣ let vs var (Simple Comparison) ⭐⭐

Feature let var
Can change value ❌ No ✅ Yes
Safer ✅ Yes ❌ Less
Thread-safe ✅ Better ❌ Risky
Performance ✅ Better ❌ Slightly less

5️⃣ Mutability with Collections ⭐⭐

Array

let arr = [1, 2, 3]
// arr.append(4) ❌
var arr2 = [1, 2, 3]
arr2.append(4) // ✅


Dictionary

let dict = ["A": 1]
// dict["B"] = 2 ❌
var dict2 = [“A”: 1]
dict2[“B”] = 2 // ✅


Set

let set: Set = [1, 2]
// set.insert(3) ❌
var set2: Set = [1, 2]
set2.insert(3) // ✅


6️⃣ let with Reference Types ⭐⭐⭐ (Very Important)

Classes are reference types.

class Person {
var name = "Amit"
}
let p = Person()
p.name = “Neha” // ✅ Allowed
// p = Person() ❌ Not allowed

📌 let prevents reassigning the reference, not changing its properties.


7️⃣ Structs & Enums with let ⭐⭐⭐

Structs & enums are value types.

struct Point {
var x: Int
}
let p = Point(x: 10)
// p.x = 20 ❌ Error

📌 Entire value becomes immutable.


8️⃣ Mutability Inside Functions ⭐⭐

func test() {
let x = 10
var y = 20
// x = 15 ❌
y = 25 // ✅
}

9️⃣ Performance & Safety ⭐⭐⭐

Why let is preferred:

✔ Safer (no accidental changes)
✔ Easier to reason about code
✔ Compiler optimizations
✔ Better concurrency support

📌 Swift encourages immutability


🔟 Common Mistakes ❌

❌ Using var everywhere
❌ Trying to modify let collections
❌ Confusing reference vs value types
❌ Reassigning let objects


📌 Interview Questions (Swift Mutability)

Q1. Difference between let and var?
👉 let is immutable, var is mutable

Q2. Can we modify properties of a let class instance?
👉 Yes

Q3. Why prefer let?
👉 Safety & performance

Q4. Why let struct is fully immutable?
👉 Value type behavior


✅ Summary

let → constant (immutable)
var → variable (mutable)
✔ Use let by default
✔ Collections follow same rules
✔ Classes allow internal mutation
✔ Structs become fully immutable
✔ Critical for Swift interviews

You may also like...