Constants and Variables
Prerequisites: Printing output
A constant or variable gives a name to a value so you can use it later.
Real-world analogy: it's a labeled box. A constant is a sealed box — once you put something in, it stays. A variable is a box you can open and refill.
Syntax
let name = "Ada" // constant: can't change
var score = 0 // variable: can change
Example
let city = "Lagos"
var temperature = 24
print(city)
print(temperature)
temperature = 27
print(temperature)
temperature += 1
print(temperature)
Expected output
Lagos
24
27
28
temperature += 1 is short for temperature = temperature + 1.
Prefer let
Use let by default, and var only when the value really needs to
change. It makes code easier to understand — if something is a let,
you know it never changes — and the compiler warns you when a
var is never modified:
warning: variable 'city' was never mutated; consider changing to 'let' constant
Naming
- Use
lowerCamelCase:firstName,totalPrice,isLoggedIn. - Names can't start with a digit or contain spaces.
- Choose descriptive names —
totalPricebeatstp.
Common mistakes
- Changing a constant:
let limit = 10
limit = 20
error: cannot assign to value: 'limit' is a 'let' constant
- Using a variable before giving it a value:
error: variable 'total' used before being initialized.
Practice
Create a constant appName and a variable launchCount starting at
0. Increase launchCount by 1 twice, then print
Notes has launched 2 times.
Hint: you can put a value inside a string with \(...) — the
Strings lesson explains it: "\(appName) has launched ...".
Show solution
let appName = "Notes"
var launchCount = 0
launchCount += 1
launchCount += 1
print("\(appName) has launched \(launchCount) times")