Repeat code while a condition is true using while.
Use repeat { ... } while to check the condition after the loop body.
while
The while loop checks the condition before each iteration.
Example
var n = 3
while n > 0 {
print(n)
n -= 1
}
print("Liftoff!")
This example counts down from 3 using a while loop.
repeat { } while
repeat runs the body first, then checks the condition.
Example
var attempts = 0
repeat {
attempts += 1
print("Attempt #\(attempts)")
} while attempts < 3
This example demonstrates repeat (do-while style).
Leave a Reply