if and else
Sprout's habit card says "Done!", "Halfway there" or "Let's start", depending on how many minutes you have logged. Choosing one of several paths is the job of if, and the order you write the branches in decides which message people see.
The rule
Checked top to bottom: the first true branch runs, and only that one.
let minutes = 12
let goal = 20
if minutes >= goal {
print("Done!")
} else if minutes >= goal / 2 {
print("Halfway there")
} else {
print("Let's start")
}
// prints "Halfway there"How Swift reads it:
- Each condition must be a real
Bool. No brackets are needed around it, but the braces are required, even for a single line. - Swift tests the conditions in order. The first one that is true runs its block, and every branch after it is skipped, even if it would also be true.
elsecatches everything left over. It is optional; without it, nothing runs when no condition is true.
if can also produce a value directly, as long as every branch gives one and there is a final else:
let message = if minutes >= goal { "Done!" } else { "Keep going" }This is handy in SwiftUI, where you often pick a word, colour or icon from the current state.
The shortcut
When conditions overlap, put the strictest one first. Walk down the list with the actual value, stop at the first true, and ignore everything below it.
The draft
if minutes >= goal / 2→ "Halfway", thenelse if minutes >= goal→ "Done!".
Drills
Answer fast — trust the rule.
With minutes = 20 and goal = 20, what does the lesson's first example print?
Which line compiles in Swift?
How many branches of one if / else if / else chain can run?
Why does let label = if done { "✓" } fail to compile?
Remember
- Checked top to bottom: the first true branch runs, and only that one.
- When conditions overlap, put the strictest first.
- Braces are required; an
ifthat produces a value needs anelse.
