Conditionals: if and else
Prerequisites: Operators
A conditional runs code only when a condition is true.
Real-world analogy: "If it's raining, take an umbrella; otherwise, wear sunglasses."
Syntax
if condition {
// runs when condition is true
} else if otherCondition {
// runs when the first was false and this one is true
} else {
// runs when none of the above were true
}
Example
let temperature = 18
if temperature > 25 {
print("It's hot")
} else if temperature > 15 {
print("It's pleasant")
} else {
print("It's cold")
}
Expected output
It's pleasant
Swift checks the conditions from top to bottom and runs only the first branch that matches.
if as an expression
Since Swift 5.9, if can produce a value directly:
let age = 20
let status = if age >= 18 { "adult" } else { "minor" }
print(status)
adult
Combining conditions
let hour = 14
let isWeekend = false
if isWeekend || hour < 9 || hour >= 17 {
print("Closed")
} else {
print("Open")
}
Open
Common mistakes
- Leaving off the braces:
if x > 5 print("big")doesn't compile. Braces are always required. - Putting conditions in the wrong order.
if score > 50beforeif score > 90means the second can never run.
Practice
Store an age and print adult for 18 and over, teen for 13–17, and
child otherwise.
Show solution
let age = 15
if age >= 18 {
print("adult")
} else if age >= 13 {
print("teen")
} else {
print("child")
}
teen