Variables & Constants (let / var)
Two kinds of boxes to store values: one you can change, one you can't.
Think of `let` as writing in pen, once it's down, it stays. `var` is writing in pencil, you can erase and rewrite it. Use pen by default; only grab the pencil when you actually need to change something.
A variable is just a labelled box that holds a value. `var name = "Ali"` makes a box you can refill later. `let name = "Ali"` makes a box that's sealed after the first value.
Swift figures out the type of the box automatically from what you put in it (this is called type inference), so you rarely write the type yourself. You can if you want clarity: `let age: Int = 8`.
Prefer `let`. It tells anyone reading the code "this never changes", which prevents bugs and lets the compiler optimise. Reach for `var` only when the value genuinely needs to change over time.
let (pen, sealed) var (pencil, refillable)
┌───────────────┐ ┌───────────────┐
│ name = "Ali" │ │ score = 0 │
└───────────────┘ └───────────────┘
│ │
change it? ──► ❌ error change it? ──► ✅ score = 10let pi = 3.14159 // constant, type inferred as Double var score = 0 // variable, can change score = 10 // ✅ allowed // pi = 3.0 // ❌ compile error: cannot assign to 'let' let name: String = "Ali" // explicit type (optional to write)
- Constant.
- A value that never changes after it's set (let).
- Variable.
- A value you can reassign later (var).
- Type inference.
- Swift guessing the type from the value, so you don't write it.
- Default to `let`; use `var` only when the value must change.
- Swift infers the type, `let x = 5` is an Int automatically.
- Reassigning a `let` is a compile-time error (caught before the app runs).