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, a new random number between 0 and 9 is generated. The while loop will continue to loop while the randomly-generated number is less than 7. Once the randomly-generated number is equal to or greater than 7, the loop will exit.

In the preceding example, the while loop checked the conditional statement prior to generating a new random number. What if we did not want to check the conditional statement prior to generating a random number? We could generate a random number when we first initialize the variable, but that would mean we would need to duplicate the code that generates the random numbers, and duplicating code is never an ideal solution. It would be preferable to use the repeat-while loop.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset