Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Control Flow  ›  Lesson

if and else

if / else 12 minAn if / else if / else chain tests Bool conditions top to bottom and runs only the first branch whose condition is true.

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.
  • else catches 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 bug in Sprout's first draftStep 1 of 4
  1. The draft

    if minutes >= goal / 2 → "Halfway", then else if minutes >= goal → "Done!".

Drills

Answer fast — trust the rule.

quick drill

With minutes = 20 and goal = 20, what does the lesson's first example print?

quick drill

Which line compiles in Swift?

quick drill

How many branches of one if / else if / else chain can run?

quick drill

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 if that produces a value needs an else.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWhy order matters

Sprout's card checks minutes >= goal / 2 for 'Halfway' before minutes >= goal for 'Done!'. Explain why users who meet their goal never see 'Done!', and how to fix it.