Looping with while loops
for
loops are great when you know how many times you intend to loop, but if you want to loop until a certain condition is met, you need a while
loop.
A while
loop has the following syntax:
while <#boolean expression#> { <#code to execute#> }
The code block will execute over and over until the Boolean expression returns false
. Therefore, it’s a common pattern to change some value in the code block that may cause the Boolean expression to change to false
.
Note
If there is no chance of the Boolean expression becoming true, the code will loop forever, which can lock up your app.
In this recipe, we will look at situations where a while
loop can be useful to repeat actions.
Getting ready
This recipe will involve simulating the random flip of a coin. To flip our coin, we will need to randomly pick either heads or tails, so we will need to use a random number generator from the Foundation...