Control Flow
Repeat While
repeat while runs the loop body once before checking the condition.
Run once before testing
repeat_while.swift
Replay: real traced execution (multi-file project)
let start = 3
var countdown = start
var ticks = 0
repeat {
ticks = ticks + 1
countdown = countdown - 1
} while countdown > 0
print("start=\(start)")
print("ticks=\(ticks)")
let start = 1
var countdown = start
var ticks = 0
repeat {
ticks = ticks + 1
countdown = countdown - 1
} while countdown > 0
print("start=\(start)")
print("ticks=\(ticks)")
let start = 5
var countdown = start
var ticks = 0
repeat {
ticks = ticks + 1
countdown = countdown - 1
} while countdown > 0
print("start=\(start)")
print("ticks=\(ticks)")
start ← 3, countdown ← 3, ticks ← 0
1let start→ 3 = 3 //@start=1, 52var countdown→ 3 = start33var ticks→ 0 = 0ticks ← 1, countdown ← 2
pass 1 of 35repeat {6 ticks→ 1 = ticks + 17 countdown→ 2 = countdown - 18} while countdown > 0All 3 passes — pass 1 is the card above pass tickscountdown1 0 → 1 3 → 2 2 1 → 2 2 → 1 3 2 → 3 1 → 0 print("start=\(start)")
10print("start=\(start3)")11print("ticks=\(ticks3)")outputstart=3 ticks=3
start ← 1, countdown ← 1, ticks ← 0
1let start→ 1 = 12var countdown→ 1 = start13var ticks→ 0 = 0ticks ← 1, countdown ← 0
5repeat {6 ticks→ 1 = ticks + 17 countdown→ 0 = countdown - 18} while countdown > 0print("start=\(start)")
10print("start=\(start1)")11print("ticks=\(ticks1)")outputstart=1 ticks=1
start ← 5, countdown ← 5, ticks ← 0
1let start→ 5 = 52var countdown→ 5 = start53var ticks→ 0 = 0ticks ← 1, countdown ← 4
pass 1 of 55repeat {6 ticks→ 1 = ticks + 17 countdown→ 4 = countdown - 18} while countdown > 0All 5 passes — pass 1 is the card above pass tickscountdown1 0 → 1 5 → 4 2 1 → 2 4 → 3 3 2 → 3 3 → 2 4 3 → 4 2 → 1 5 4 → 5 1 → 0 print("start=\(start)")
10print("start=\(start5)")11print("ticks=\(ticks5)")outputstart=5 ticks=5
Tick the Countdown
startis3.countdownbegins at3.- The repeat block runs before the condition check.
- Each pass adds one tick and subtracts one from
countdown. - The printed tick count is
3. | Countdown before pass | Ticks after pass | | --- | --- | |3|1| |2|2| |1|3|
repeat while
A `repeat while` loop is useful when the body must execute at least once, even if the condition becomes false immediately.
Exercise: repeat_while.swift
Use repeat while to count ticks while a countdown moves toward zero