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 the current state in the code block that may cause the Boolean expression to change to false
.
Note
If there is no chance that the Boolean expression can become true, the code will loop forever, which can lock up your app.
Getting ready
Let's work out how many times in a row we can flip a coin and get heads.
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 framework. We will discuss Foundation further in Chapter 5, Beyond the Standard Library, but for now, we just need to import the Foundation framework:
import Foundation...