while Loops

The classic for loop can also be expressed as a while loop.

Listing 6.6  A while loop

...
var i = 1
while i < 6 {
    ++myFirstInt
    print(myFirstInt)
    ++i
}

Like the for loop, this while loop initializes an incrementer (var i = 1), evaluates a condition (i < 6), executes code if the condition is valid (++myFirstInt, print(myFirstInt), and increments the counter (++i)), and then returns to the top of the while loop to determine whether the loop should continue iterating.

while loops are best for circumstances in which the number of iterations the loop will pass through is unknown. For example, imagine a simple space shooter game with a spaceship that continuously fires its blasters so long as the spaceship has shields. ...

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.