Chapter 9: Swift Variables
1. What is a variable in Swift? (the big picture)
A variable is a named storage location in memory that holds a value.
In Swift you have two kinds of these storage locations:
| Keyword | Meaning | Can you change the value later? | Real-life analogy |
|---|---|---|---|
| let | constant – immutable | No | Your birth date, your Aadhaar number |
| var | variable – mutable | Yes | Your bank balance, current temperature |
Golden rule that almost every good Swift developer follows (2025 style):
Use let by default Use var only when you are sure the value will actually change
This is probably the most important habit to develop early.
2. Basic syntax – declaring variables
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Constant (preferred in most cases) let pi = 3.14159 let maximumUsers = 1000 let appName = "MyTodoApp" // Variable (only when it will change) var score = 0 var currentTemperature = 28.6 var username = "guest123" |
After declaration:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
// This is allowed score = 10 score += 50 currentTemperature = 29.2 username = "player_456" // This will NOT compile – good! pi = 3.14 // Error: Cannot assign to value: 'pi' is a 'let' constant |
3. Type inference – Swift usually knows the type
Swift is very smart — you rarely need to write the type.
|
0 1 2 3 4 5 6 7 8 9 10 |
let age = 25 // Swift knows → Int let height = 1.68 // → Double let isStudent = true // → Bool let name = "Aarav" // → String let emoji = "🔥" // → String (not Character!) |
But you can write the type when it makes code clearer:
|
0 1 2 3 4 5 6 7 8 9 |
let maxFileSize: Int64 = 5_000_000_000 let taxRate: Double = 0.18 let userID: UUID = UUID() let status: HTTPStatus = .ok |
When should you write the type explicitly?
- Working with very specific number types (Int32, UInt64, Float, etc.)
- When the inferred type might be surprising
- In function parameters / return types (very common)
- When reading code is easier with explicit types
4. Side-by-side comparison with other languages
| Language | Constant style | Variable style | Swift style (modern) |
|---|---|---|---|
| C / C++ | const int max = 100; | int count = 0; | let max = 100 / var count = 0 |
| Java | final int MAX = 100; | int count = 0; | let / var |
| Python | (no real constant) | count = 0 | let / var |
| Swift | let max = 100 | var count = 0 | prefer let |
Swift encourages immutability much more strongly than most languages.
5. Very common beginner mistakes (and correct way)
| Wrong / bad habit | Why it’s bad | Better way |
|---|---|---|
| var name = “Rahul” when name never changes | Creates false expectation that it will change | let name = “Rahul” |
| var age: Int = 25 everywhere | Unnecessary noise | let age = 25 (type inference) |
| var counter = 0 and then never changing it | Misleading | let initialCount = 0 |
| Force-unwrapping optionals inside variables | var name = optionalName! → crashes easily | var name = optionalName ?? “Unknown” |
| Declaring everything as var “just in case” | Loses safety & clarity | Start with let, change to var only if needed |
6. Practical real-world examples
Example 1 – Game score
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
let maxLives = 3 // never changes var currentLives = maxLives // changes during game var score = 0 // changes a lot // later in code... score += 100 currentLives -= 1 if currentLives == 0 { print("Game Over! Final score: \(score)") } |
Example 2 – User profile
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
let userID = UUID() // never changes let registeredOn = Date() // fixed var displayName = "guest_123" var profilePictureURL: URL? // can be nil or change var isPremium = false // later... displayName = "Aarav_007" isPremium = true |
Example 3 – Temperature converter (shows let vs var clearly)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
func convertToCelsius(fahrenheit: Double) -> Double { let adjusted = fahrenheit - 32 // never changes inside function let multiplier = 5.0 / 9.0 // constant return adjusted * multiplier } var currentTempF = 98.6 var currentTempC = convertToCelsius(fahrenheit: currentTempF) // later... currentTempF = 104.0 currentTempC = convertToCelsius(fahrenheit: currentTempF) |
7. Naming conventions – what real Swift developers do
| Kind of name | Convention | Example |
|---|---|---|
| Constants (let) | camelCase or UPPER_CASE for global | maxRetryCount, API_KEY |
| Variables (var) | camelCase | currentUser, totalPrice |
| Private properties | Often private var | private var internalCache |
| Global constants | UPPER_CASE_WITH_UNDERSCORES (rare) | MAX_UPLOAD_SIZE_BYTES |
Very common pattern in modern SwiftUI / UIKit:
|
0 1 2 3 4 5 6 7 |
private let cellReuseIdentifier = "UserCell" private var users: [User] = [] |
8. Quick cheat sheet – when to choose let vs var
| Situation | Use let or var? | Why? |
|---|---|---|
| Value will never change | let | Safety + clarity |
| Value changes in one small scope | var | Normal |
| Loop variable (for-in) | let (default) | You rarely change it |
| Property that gets set once (like in init) | let | Expresses intent |
| Counter, score, position, status | var | Obviously changes |
| Model / struct property that should not change | let | Makes data safer |
9. Mini practice – try to fix these
|
0 1 2 3 4 5 6 7 8 9 10 11 |
// Try to improve these declarations var firstName = "Sneha" // never changes var age = 24 // never changes later var totalPrice = 1499.99 // calculated once var counter = 0 // used in for loop but never reassigned |
Expected better versions:
|
0 1 2 3 4 5 6 7 8 9 |
let firstName = "Sneha" let age = 24 let totalPrice = 1499.99 // counter → usually let inside for-in |
Would you like to continue with:
- Optionals (String?, Int?, etc.) – very important next step
- Computed properties (variables that calculate their value)
- Variables inside functions vs properties in structs/classes
- Type aliases (typealias UserID = Int64)
- Or move to another topic (constants in detail, printing variables, etc.)
Just tell me what you want next — I’ll continue in the same detailed, teacher-like way 😊
