Swift If...Else
Programs constantly make decisions: is the password long enough, is the cart empty, did the player win? In Swift you make these decisions with if, else if and else. Each condition must be a real Bool — Swift never treats a number or a string as "truthy".
The if statement
An if block runs only when its condition is true. The braces are always required, but the parentheses around the condition are not (and Swift style leaves them out).
let temperature = 31
if temperature > 30 {
print("It's hot today. Drink some water!")
}
print("Weather check finished.")It's hot today. Drink some water!
Weather check finished.
Change temperature to 20 and run again: the first message disappears, the second one still prints.
else and else if
Use else for the "otherwise" case, and chain else if to test several conditions in order. Swift checks them top to bottom and runs only the first branch whose condition is true.
let score = 74
if score >= 90 {
print("Grade: A")
} else if score >= 80 {
print("Grade: B")
} else if score >= 70 {
print("Grade: C")
} else {
print("Grade: F")
}Grade: C
Tip: Order matters. If you tested
score >= 70first, a score of 95 would also get a C, because the first matching branch wins.
Conditions must be Bool
In C or JavaScript you can write if count { … }. Swift refuses this: the condition has to be a Bool. This rule catches a whole family of bugs at compile time.
let count = 3
if count {
print("Not empty")
}error: emit-module command failed with exit code 1 (use -v to see invocation)
<source>:3:4: error: type 'Int' cannot be used as a boolean; test for '!= 0' instead
1 | let count = 3
2 |
3 | if count {
| `- error: type 'Int' cannot be used as a boolean; test for '!= 0' instead
4 | print("Not empty")
5 | }
The fix is to say what you mean: if count != 0 or if count > 0.
Combining conditions
Use the logical operators && (and), || (or) and ! (not) to build bigger conditions. You can also separate conditions with a comma, which works like &&:
| Form | Meaning |
|---|---|
a && b |
both must be true |
a || b |
at least one must be true |
!a |
flips true/false |
if a, b { } |
same as a && b (commonly used with optionals) |
let age = 19
let hasTicket = true
let isVIP = false
if age >= 18 && hasTicket {
print("Welcome to the concert.")
}
if isVIP || age >= 65 {
print("Free drink included.")
} else {
print("Drinks are available at the bar.")
}
if hasTicket, !isVIP {
print("Standard entrance: gate B")
}Welcome to the concert.
Drinks are available at the bar.
Standard entrance: gate B
if as an expression
Since Swift 5.9, if can produce a value. Each branch must be a single expression of the same type, and an else is mandatory so that a value always exists:
let battery = 15
let status = if battery > 50 {
"Good"
} else if battery > 20 {
"Low"
} else {
"Critical — please charge"
}
print("Battery: \(status)")Battery: Critical — please charge
The ternary operator
For a quick choice between two values, the ternary operator condition ? valueIfTrue : valueIfFalse is even shorter:
let items = 1
let word = items == 1 ? "item" : "items"
print("You have \(items) \(word) in your cart.")
let isNight = true
print(isNight ? "🌙 Dark mode on" : "☀️ Light mode on")You have 1 item in your cart.
🌙 Dark mode on
Note: Use the ternary operator for short, readable choices. When the logic grows, an
if/else(or aswitch, coming next) is clearer.
Test yourself
What happens when you write if 1 { print("yes") } in Swift?
- It prints yes
- It prints nothing
- It is a compile error
- It crashes at runtime
In an if / else if / else chain, how many branches can run?
- All branches whose condition is true
- At most one
- Exactly two
- Only the else branch
What does let x = 5 > 3 ? "big" : "small" store in x?
- "small"
- true
- "big"
- 5