Making decisions in code
People decide things from conditions: if it is raining, take an umbrella; if you are hungry, eat. An if statement lets a program do the same. It runs a block of code only when a condition is true.
var isRainy = true
if isRainy {
print("I bring an umbrella")
}
I bring an umbrella
The general shape is:
if condition {
// runs only when the condition is true
}
After the keyword if comes the condition, then a block in curly braces. Swift doesn't need parentheses around the condition, although if (isRainy) { ... } is also accepted. The braces are required, even for a single line, so if isRainy print("...") is a compile error.
Boolean conditions
The condition must be a Bool, a value that is either true or false. When it is true, the block runs. When it is false, the block is skipped and the program continues after the closing brace:
var amHungry = false
if amHungry {
print("I have breakfast")
}
print("done")
done
Nothing is printed for the if, because amHungry is false, but the later print still runs.
Swift is strict here. A number is not a condition. This code doesn't compile:
let flag = 1
if flag {
print("yes")
}
error: type 'Int' cannot be used as a boolean; test for '!= 0' instead
Write the comparison out instead, for example flag != 0. Comparisons like n > 3 and name == "Ann" are expressions that produce a Bool, so they work directly as conditions. A condition that is already a Bool needs no == true.
Adding else
An else block runs when the condition is false. It takes no condition of its own, because it covers every case the if didn't. Exactly one of the two blocks runs:
let passed = false
if passed {
print("Passed the test")
} else {
print("Failed")
}
Failed
The closing brace of the if block, the word else and the opening brace of the else block usually share a line: } else {. To test further conditions in order, chain them with else if:
let n = 5
if n > 8 {
print("big")
} else if n > 3 {
print("medium")
} else {
print("small")
}
medium
Combining conditions
Three operators build bigger conditions out of smaller ones: && (and) is true when both sides are true, || (or) is true when at least one side is, and ! (not) flips a value:
let age = 20
let hasTicket = true
if age >= 18 && hasTicket {
print("welcome")
}
if age < 18 || !hasTicket {
print("stop")
} else {
print("ok")
}
welcome
ok
The first condition holds because both parts are true. In the second, age < 18 is false and !hasTicket is false, so the else block runs. Both operators stop early: if the left side of && is false, the right side is never evaluated.
The exercise
The starter code declares let passed: Bool = true. The task has three steps:
- Write
if passed {. The constant is already aBool, so it is the whole condition. - Inside the block, print
"Passed the test". - Close with
} else {, print"Failed", and close the block with}.
let passed: Bool = true
if passed {
print("Passed the test")
} else {
print("Failed")
}
Passed the test
With passed set to false, the same code prints Failed.
Common mistakes
- Using
=instead of==.if n = 3is rejected withuse of '=' in a boolean context, did you mean '=='?. - Leaving out the braces. They are mandatory in Swift.
- Using a non-Bool condition. Integers, strings and optionals must be compared or unwrapped first.
- Putting a condition on
else. Useelse iffor that. - Starting a new line before
else. It is accepted by the compiler, but keeping} else {together is the common style.
Key takeaways
if condition { ... }runs the block only when the condition istrue.- The condition must be a
Bool, and parentheses around it are optional. elsecovers the case where the condition is false, andelse ifadds more conditions.
