While
A while loop performs a set of statements until a condition becomes false. These kinds of loops are best used when the number of iterations isn’t known before the first iteration begins.
Swift provides two kinds of while loops:
whileevaluates its condition at the start of each pass through the loop.repeat-whileevaluates its condition at the end of each pass through the loop.
While
A while loop starts by evaluating a single condition. If the condition is true, a set of statements is repeated until the condition becomes false.
var square = 0
var diceRoll = 0
while square < 25 {
// Roll the dice
diceRoll += 1
if diceRoll == 7 { diceRoll = 1 }
// Move
square += diceRoll
}
print("Game over!")
Repeat-While
The other variation of the while loop, known as the repeat-while loop, performs a single pass through the loop block first, before considering the loop’s condition. It then continues to repeat the loop until the condition is false.
var i = 0
repeat {
print(i)
i += 1
} while i < 5
// Prints 0, 1, 2, 3, 4