Chapter 10: Variables
variables in Swift.
Imagine we are sitting together, I’m showing you on my screen, and I explain everything slowly with small examples you can immediately try yourself. We go step by step so you really understand what, why, and how Swift wants you to think about variables.
1. Two kinds of “boxes” in Swift: let vs var
In Swift there are two different kinds of named storage:
| Keyword | Name | Can the value change later? | Real-life analogy | When should you use it? |
|---|---|---|---|---|
| let | constant | No — never again | Your date of birth, PAN card number, height | Almost always (the default choice) |
| var | variable | Yes — you can change it | Current bank balance, score in a game, temperature | Only when you really need to change it |
The most important habit to build right now (this separates beginners from experienced Swift developers):
Start with let Change it to var only when you actually need to re-assign a new value later
This is not just a style rule — it’s a safety feature built into the language.
2. Very first examples – try these right now
Open a playground and type:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// These can NEVER change → use let let birthYear = 2001 let pi = 3.141592653589793 let maximumScore = 999_999 let appVersion = "2.4.1" let isProduction = true // These WILL change → use var var currentScore = 0 var livesLeft = 3 var temperature = 28.4 var username = "guest_987" |
Now try this:
|
0 1 2 3 4 5 6 7 8 9 10 |
currentScore = 150 // ✅ OK livesLeft = 2 // ✅ OK temperature = 29.1 // ✅ OK // birthYear = 2002 // ❌ Compile error – good! |
3. Type inference – Swift is smart
You usually don’t need to write the type — Swift guesses it correctly.
|
0 1 2 3 4 5 6 7 8 9 10 |
let age = 24 // Swift understands → Int let height = 1.72 // → Double let lovesCoffee = true // → Bool let firstName = "Aarav" // → String let emoji = "🚀" // → String |
But sometimes you want to be very explicit:
|
0 1 2 3 4 5 6 7 8 9 |
let maxFileSizeBytes: Int64 = 10_000_000_000 let taxPercentage: Double = 0.18 let userIdentifier: UUID = UUID() let httpStatus: UInt16 = 200 |
Quick rule of thumb (2025 style):
- 90–95% of the time → use type inference (let name = “Priya”)
- Write the type explicitly when:
- The type is not obvious
- You need a specific size (Int32, UInt64, Float, …)
- You’re working with legacy C/Objective-C APIs
- You want to make the code easier to understand at a glance
4. Very common beginner mistakes (and how to fix them)
| Bad code (very frequent) | Why it’s problematic | Better style |
|---|---|---|
| var name = “Sneha” (never changed again) | Misleads readers — looks like it might change | let name = “Sneha” |
| var age: Int = 27 everywhere | Unnecessary noise — Swift already knows it’s Int | let age = 27 |
| var counter = 0 … and then never changing it | False expectation | let initialValue = 0 or let start = 0 |
| var optionalValue = someOptional! | Very dangerous — crashes easily | var value = someOptional ?? defaultValue |
| Declaring everything var “just in case” | Lose safety, clarity, and compiler help | Start with let, change only when necessary |
5. Real-world examples – how variables are really used
Example 1 – Simple game
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
let maxLives = 5 let pointsPerCoin = 100 var livesRemaining = maxLives var currentScore = 0 var coinsCollected = 0 // Later in game loop... coinsCollected += 1 currentScore += pointsPerCoin livesRemaining -= 1 print("Score: \(currentScore) | Lives: \(livesRemaining)") |
→ maxLives and pointsPerCoin are let → they never change → the others are var → they change during gameplay
Example 2 – User profile screen
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
struct UserProfile { let userID: UUID // never changes let joinedDate: Date // never changes var displayName: String // user can change it var profilePhotoURL: URL? // can be updated var isPremiumMember: Bool // can change } |
Example 3 – Temperature tracker
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let freezingPointCelsius = 0.0 let boilingPointCelsius = 100.0 var currentTemperatureC = 23.7 // later... currentTemperatureC = 28.2 |
6. Naming – what experienced developers actually do
| Kind of thing | Naming style in modern Swift (2025–2026) | Examples |
|---|---|---|
| Constants (let) | camelCase or UPPER_CASE for global | maxRetryCount, API_BASE_URL |
| Variables (var) | camelCase | currentUser, totalAmount |
| Private properties | Often start with private var | private var cache |
| Global / static constants | Usually UPPER_CASE_WITH_UNDERSCORES | MAX_UPLOAD_SIZE_BYTES |
| Local variables (inside func) | Descriptive camelCase | indexOfSelectedRow, newPassword |
Very common pattern in real apps:
|
0 1 2 3 4 5 6 7 8 |
private let cellReuseIdentifier = "ProductCell" private var products: [Product] = [] private var isLoading = false |
7. Quick decision table – let or var?
| Situation | Almost always choose | Reason / feeling you should have |
|---|---|---|
| Value will never change again | let | “This is fixed forever” |
| Value is calculated once and never reassigned | let | “This is a result — it’s final” |
| Loop variable (for-in) | let (default) | You almost never reassign it |
| Property set only in init | let | “This is part of the identity of the object” |
| Counter, accumulator, score, position, status | var | “This clearly changes during execution” |
| Model field that logically shouldn’t change | let | Makes data safer & easier to reason about |
8. Very small practice – improve these lines
Try rewriting them using better let/var choices:
|
0 1 2 3 4 5 6 7 8 9 10 |
var firstName = "Rahul" var age = 25 var totalPrice = 2499.00 var counter = 0 var settings = Settings() |
Better versions (one possible answer):
|
0 1 2 3 4 5 6 7 8 9 10 |
let firstName = "Rahul" let age = 25 let totalPrice = 2499.00 let startingCounter = 0 // or just use let in the loop let settings = Settings() |
Next step — which topic would you like to go deeper into?
- Optionals (String?, Int?, nil values)
- Computed properties (variables that calculate their value)
- Variables vs constants inside functions vs in structs/classes
- When to use var parameters in functions
- Or any other topic you want (constants in more detail, naming, printing variables…)
Just tell me — we’ll continue in exactly the same detailed, step-by-step, teacher-like way 😊
