Swift Repeat/While Loop
Swift Repeat/While Loop
Use repeat { ... } while condition to run the body at least once.
Repeat/while Loop Example
This example uses a repeat/while loop to print "Try #1" and "Try #2".
Example
var attempts = 0
repeat {
attempts += 1
print("Attempt #\(attempts)")
} while attempts < 3
This example demonstrates repeat (do-while style).
Tip: Avoid infinite loops. Ensure the loop condition will eventually become false.
Runs Once Even If Condition Is False
Because repeat checks the condition after the body, it executes at least once.