while Loops

A while loop executes the code inside its body so long as a condition is true. You can write while loops to do many of the same things you have seen in for loops above. For example, a while loop that replicates the for loop in Listing 6.1 can be expressed like so:

Listing 6.5 A while loop

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

Figure 6.5 shows the flow of execution in this code.

Figure 6.5 while loop diagram

A flowchart depicts the “while” loop diagram.

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.