Loops are used to execute a block of code repeatedly as long as a certain condition is true.
A while loop evaluates its condition at the start of each pass through the loop.
It is best used when the number of iterations is not known before the loop begins.
while LoopThe while loop checks a condition. If it is true, the code inside the block executes. It then checks the condition again, and repeats until the condition becomes false.
var counter = 1while counter <= 5 { print("Count is \(counter)") counter += 1 // Don't forget to increase the counter! }
Warning: If you forget to update the variable being checked in the condition (like counter += 1), the loop will run forever. This is called an infinite loop!
repeat-while LoopThe repeat-while loop is Swift's version of the do-while loop found in other languages.
The key difference is that it evaluates its condition at the end of each pass.
This guarantees that the code block will execute at least once, regardless of the condition.
var attempts = 1repeat { print("Attempt number \(attempts)") attempts += 1 } while attempts < 1
In the example above, even though attempts < 1 is false immediately, the print statement executes exactly one time.
while loop when you want to check the condition before executing the code.repeat-while loop when you absolutely must run the code block at least one time before making the decision to stop.Which loop guarantees that its code block will be executed at least once?