How it works...

In our function, we start by keeping track of how many coin flips in a row are heads and keep a reference to the current coin flip, which will form the condition for the while loop:

func howManyHeadsInARow() -> Int { 

var numberOfHeadsInARow = 0
var currentCoinFlip = CoinFlip.flipCoin()
//...
}

In our while loop, we will continue to loop while the current coin flip is heads; while that is true, the code in the following block is executed:

while currentCoinFlip == .heads { 
numberOfHeadsInARow = numberOfHeadsInARow + 1
currentCoinFlip = CoinFlip.flipCoin()
}

Within the code block, we add one to our running total and we reflip the coin. Since we are flipping the coin and assigning it to currentCoinFlip, it will get rechecked on the next loop, which meets our requirement of changing the state to ensure that we don't loop forever.

As soon as the coin flip is tails, the while loop condition will be false, and so the execution will move on and return the running total we have been keeping:

return numberOfHeadsInARow 

Now, every time you call the function, the coin will be randomly flipped and the number of heads in a row will be returned, so each time it's called, you may get a different value returned. Try it as follows:

let noOfHeads = howManyHeadsInARow()