while, repeat-while, break and continue
Sprout asks new users for a daily goal and must keep asking until they type a real number. It also counts a streak by walking back through the days until it meets one that was missed. Neither knows in advance how many passes it needs. That is when for gives way to while.
The rule
whilechecks first,repeatchecks after;continueskips,breakleaves.
A while loop tests its condition before every pass. If the condition is false from the start, the body never runs:
var minutes = 0
while minutes < 30 {
minutes += 10
}
// minutes is 30 after three passesA repeat-while loop runs the body first and tests afterwards, so it always runs at least once. That fits "ask, then check the answer":
var goal = 0
repeat {
print("How many minutes a day?")
goal = Int(readLine() ?? "") ?? 0
} while goal <= 0Inside any loop:
continueends this pass early and jumps to the next one.breakends the whole loop immediately.
let week = ["done", "rest", "done", "missed", "done"]
var streak = 0
for day in week {
if day == "rest" { continue } // rest days do not count or break it
if day == "missed" { break } // the streak ends here
streak += 1
}
// streak is 2Make sure something in a while body moves it toward stopping. A condition that never becomes false is an infinite loop, and the app freezes.
The shortcut
Pick the loop by one question: must the body run at least once? Yes → repeat-while. No, and the count is unknown → while. Count known → for-in. Then trace passes on paper, marking each continue as "skip to next" and each break as "exit now".
Pass 1: "done"
Not rest, not missed.
streakbecomes 1.
Drills
Answer fast — trust the rule.
How many times does the body of while count > 10 { count -= 1 } run when count starts at 5?
Which loop always runs its body at least once?
Inside a loop, what does continue do?
With the week ["done", "done", "missed", "rest", "done"], what streak does the lesson's loop give?
Remember
whilechecks first,repeatchecks after;continueskips,breakleaves.- Must the body run once?
repeat. Unknown count?while. Known?for. - Every
whileneeds something that moves it toward false.
