while Loops

A while loop executes the code inside its body for as long as a specified condition is true. You can write while loops to do many of the same things you have seen in for loops above. Start with a while loop that replicates the for loop in Example 6.1, “A for-in loop”:

Example 6.5. A while loop
...
var i = 1
while i < 6 {
    myFirstInt += 1                                        (5 times)
    print(myFirstInt)                                      (5 times)
    i += 1                                                 (5 times)
}

Figure 6.5, “while loop diagram” shows the flow of execution in this code.

Figure 6.5. while loop diagram
while loop diagram

This while loop initializes a control variable (var i = 1), evaluates a condition (i < 6), executes code if the condition is valid (myFirstInt ...

Get Swift Programming: The Big Nerd Ranch Guide, 3rd Edition 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.