Swift loops: the repeat-while loop

By

Learn how the repeat-while loop works in Swift, where the condition is checked at the end so the loop body always runs at least once before repeating.

~~~

This tutorial belongs to the Swift series

A repeat-while loop in Swift is similar to the while loop, but the condition is checked at the end, after the loop block. This means the loop body always runs at least once. Then the condition is evaluated, and if it’s true, the block runs again:

repeat {
    //statements...
} while [condition]

If you come from other languages, this is Swift’s version of the do-while loop. Swift renamed it because do is already used for error handling.

Example:

var item = 0
repeat { //repeats 3 times
    print(item)
    item += 1
} while item < 3

This prints:

0
1
2

How is it different from while?

A while loop checks the condition first. If the condition is false from the start, the body never runs:

var item = 5
while item < 3 {
    print(item) //never runs
    item += 1
}

The same setup with repeat-while runs the body once, because the check happens after:

var item = 5
repeat {
    print(item) //prints 5, once
    item += 1
} while item < 3

When would you use it?

Reach for repeat-while when the work must happen before you can know whether to repeat it.

A classic case is asking for input and validating it. You need to read the input at least once before you can decide if it’s valid:

var guess: Int
repeat {
    guess = Int.random(in: 1...10)
    print("Trying \(guess)")
} while guess != 7

Here we can’t check the guess before making one. The loop keeps generating numbers until it hits 7, and the body is guaranteed to run at least one time.

In practice, while covers most situations. But when you find yourself duplicating the loop body once before a while loop, that’s the signal you wanted repeat-while instead.

Watch out for infinite loops

The most common mistake with repeat-while is forgetting to change the value the condition depends on:

var item = 0
repeat {
    print(item)
} while item < 3 //never ends

Nothing inside the block updates item, so the condition stays true forever and the loop never exits. Your program hangs.

The fix is making sure something in the body moves the condition toward false, like the item += 1 in the earlier example. Before writing the condition, ask yourself: what makes this eventually become false?

Tagged: Swift · All topics
~~~

Related posts about swift: