O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using the while loop

The while loop starts by evaluating a conditional statement and then repeatedly executes a block of code while the conditional statement is true. The format for the while statement is as follows:

while condition {  
  block of code 
} 

Let's look at how to use a while loop. In the following example, the while loop will continue to execute the block of code while the randomly-generated number is less than 7. In this example, we are using the arc4random_uniform() function to generate a random number between 0 and 9:

var ran = 0  
while ran < 7 { 
  ran = Int(arc4random_uniform(10)) 
} 

In the preceding example, we began by initializing the ran variable to 0. The while loop then checks that variable and; if the value is less than 7, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required