repeat while runs the loop body once before checking the condition.

Run once before testing

start
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)")
  1. start ← 3, countdown ← 3, ticks ← 0

    1let start→ 3 = 3  //@start=1, 52var countdown→ 3 = start33var ticks→ 0 = 0
  2. ticks ← 1, countdown ← 2

    pass 1 of 3
    5repeat {6    ticks→ 1 = ticks + 17    countdown→ 2 = countdown - 18} while countdown > 0
    All 3 passes — pass 1 is the card above
    passtickscountdown
    10 13 2
    21 22 1
    32 31 0
  3. print("start=\(start)")

    10print("start=\(start3)")11print("ticks=\(ticks3)")
    outputstart=3
    ticks=3
  1. start ← 1, countdown ← 1, ticks ← 0

    1let start→ 1 = 12var countdown→ 1 = start13var ticks→ 0 = 0
  2. ticks ← 1, countdown ← 0

    5repeat {6    ticks→ 1 = ticks + 17    countdown→ 0 = countdown - 18} while countdown > 0
  3. print("start=\(start)")

    10print("start=\(start1)")11print("ticks=\(ticks1)")
    outputstart=1
    ticks=1
  1. start ← 5, countdown ← 5, ticks ← 0

    1let start→ 5 = 52var countdown→ 5 = start53var ticks→ 0 = 0
  2. ticks ← 1, countdown ← 4

    pass 1 of 5
    5repeat {6    ticks→ 1 = ticks + 17    countdown→ 4 = countdown - 18} while countdown > 0
    All 5 passes — pass 1 is the card above
    passtickscountdown
    10 15 4
    21 24 3
    32 33 2
    43 42 1
    54 51 0
  3. print("start=\(start)")

    10print("start=\(start5)")11print("ticks=\(ticks5)")
    outputstart=5
    ticks=5

Tick the Countdown

  1. start is 3.
  2. countdown begins at 3.
  3. The repeat block runs before the condition check.
  4. Each pass adds one tick and subtracts one from countdown.
  5. 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