Swift Variables and Constants
Every program stores information. A variable holds data that can change, while a constant holds data that stays the same. Swift uses two keywords to create these: var for variables and let for constants.
The Box Analogy
┌──────────────────────────────────────────────┐
│ Memory as Labeled Boxes │
│ │
│ var score = 0 → [ score | 0 ] ✏️ │
│ can change anytime │
│ │
│ let pi = 3.14 → [ pi | 3.14] 🔒 │
│ locked, never changes│
└──────────────────────────────────────────────┘
Think of var as a whiteboard — you can erase and rewrite it. Think of let as text carved in stone — it is written once and stays forever.
Creating a Variable
var playerName = "Alex"
playerName = "Jordan" // Works — variables can change
The variable playerName starts as "Alex" and later changes to "Jordan". This is perfectly valid.
Creating a Constant
let maxScore = 100
// maxScore = 200 // Error! You cannot change a constant
Trying to change maxScore causes an error. Swift enforces this rule at compile time — before the app runs.
Why Use Constants
Swift encourages using let by default. When data cannot change accidentally, bugs become rarer. Use var only when the value genuinely needs to update.
Naming Rules
Swift variable names follow these rules:
- Start with a letter or underscore — not a number
- Use letters, numbers, and underscores only
- Names are case-sensitive:
scoreandScoreare two different names - Swift convention uses camelCase:
playerScore,totalItems
Multiple Assignments at Once
var x = 5, y = 10, z = 15
Swift lets you declare multiple variables on one line using commas.
Changing a Variable
var temperature = 30
temperature = 35
temperature = temperature + 2
print(temperature) // 37
Each line updates temperature. The final print shows 37.
Real-World Comparison
┌──────────────────────────────────────────────┐
│ Real Life vs Swift │
│ │
│ Bank Balance (changes daily) → var │
│ Date of Birth (never changes)→ let │
│ Cart total (updates always) → var │
│ Math constant like π (fixed) → let │
└──────────────────────────────────────────────┘
Printing Variables
var city = "Mumbai"
print("I live in \(city)") // I live in Mumbai
The \() syntax inserts a variable's value directly into a string. This is called string interpolation.
