repeat-while Loops

Swift also supports a type of while loop called the repeat-while loop. The repeat-while loop is called a do-while loop in other languages. The difference between while and repeat-while loops is when they evaluate their condition. The while loop evaluates its condition before stepping into the loop. This means that the while loop may not ever execute, because its condition could be false when it is first evaluated. The repeat-while loop, on the other hand, executes its loop at least once, and then evaluates its condition. The syntax for the repeat-while loop demonstrates this difference.

repeat {
    // Fire blasters!
    print("Fire blasters!")
} while shields > 0

In this repeat-while version of the space shooter game, ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.