Swift Mutability (let vs var)
🔐 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.
📌 Use let by default.
3️⃣ var – Mutable (Variable) ⭐
A var value can be changed.
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
Dictionary
Set
6️⃣ let with Reference Types ⭐⭐⭐ (Very Important)
Classes are reference types.
📌 let prevents reassigning the reference, not changing its properties.
7️⃣ Structs & Enums with let ⭐⭐⭐
Structs & enums are value types.
📌 Entire value becomes immutable.
8️⃣ Mutability Inside Functions ⭐⭐
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
