Swift Variables & Constants
A program stores data in named containers. Swift has two kinds:
var— a variable, whose value can change later.let— a constant, whose value is set once and never changes.
Declaring variables and constants
var stepsToday = 4200 // can change
let dailyGoal = 10000 // fixed
stepsToday = stepsToday + 1800
print("Steps: \(stepsToday) of \(dailyGoal)")Steps: 6000 of 10000
Trying to change a constant is a compile-time error — Swift protects you from accidentally overwriting values:
let maxPlayers = 4
maxPlayers = 5error: emit-module command failed with exit code 1 (use -v to see invocation)
<source>:2:1: error: cannot assign to value: 'maxPlayers' is a 'let' constant
1 | let maxPlayers = 4
| `- note: change 'let' to 'var' to make it mutable
2 | maxPlayers = 5
| `- error: cannot assign to value: 'maxPlayers' is a 'let' constant
Tip: Start with
leteverywhere and switch tovaronly when you really need to change the value. Code with fewer moving parts is easier to understand — and the compiler even warns you when avaris never modified.
Type annotations
Usually Swift infers the type from the initial value. You can also write it explicitly with a colon after the name:
let city: String = "Lisbon"
var temperature: Double = 18 // 18 becomes 18.0 because the type is Double
let isRaining: Bool = false
print(city, temperature, isRaining)Lisbon 18.0 false
A type annotation is required when you declare a constant without giving it a value immediately. Swift then checks that it is assigned exactly once before use:
let greeting: String
let hour = 9
if hour < 12 {
greeting = "Good morning"
} else {
greeting = "Good afternoon"
}
print(greeting)Good morning
Several declarations on one line
var x = 0, y = 0, z = 0
let red = 255, green = 128, blue = 0
x += 5
print(x, y, z)
print(red, green, blue)5 0 0
255 128 0
Naming rules
| Rule | Valid | Invalid |
|---|---|---|
| Must not start with a digit | player1 |
1player |
| No spaces or operators | firstName |
first name, first-name |
| Not a reserved keyword (unless in backticks) | `class` |
class |
| Case-sensitive | count ≠ Count |
— |
Names may contain almost any Unicode character, so let π = 3.14159 or let café = "open" are legal. Stick to readable English names in real projects.
A variable's type never changes
Once a variable has a type, it keeps it. You can change the value, but not store a different kind of value:
var score = 10
score = 25 // fine: still an Int
score = "high" // error: not an Interror: emit-module command failed with exit code 1 (use -v to see invocation)
<source>:3:9: error: cannot assign value of type 'String' to type 'Int'
1 | var score = 10
2 | score = 25 // fine: still an Int
3 | score = "high" // error: not an Int
| `- error: cannot assign value of type 'String' to type 'Int'
let vs var at a glance
let |
var |
|
|---|---|---|
| Can be reassigned | No | Yes |
| Must be initialised before use | Yes | Yes |
| Typical use | values that stay fixed: settings, results, input | counters, totals, state that changes |
Test yourself
Which declaration creates a value that can be changed later?
- let total = 0
- var total = 0
- const total = 0
- val total = 0
What does var price: Double = 5 store?
- The Int 5
- The Double 5.0
- The String "5"
- It does not compile
After var level = 1, which assignment fails?
- level = 2
- level += 10
- level = "two"
- level = level * 3