while and repeat-while Loops
A while loop keeps repeating code as long as a condition stays true, and repeat-while does the same but always runs the code at least once first.
In this page:
Basic while Loop
A while loop checks its condition before every iteration, so its body might not run at all if the condition starts false.
Example: Basic while Loop
var countdown = 3
while countdown > 0 {
print("T-minus \(countdown)")
countdown -= 1
}
print("Liftoff!")
Login to try C/C++/Java/PHP code in the editor
repeat-while Loop
A repeat-while loop checks its condition after running the body, guaranteeing the body executes at least once even if the condition is initially false.
Note: Compare this to a while loop with the same condition placed before the body -- repeat-while always runs once first.
Example: repeat-while Loop
var attempts = 0
repeat {
attempts += 1
print("Attempt number \(attempts)")
} while attempts < 3
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Writing a
whileloop whose condition never becomes false, creating an infinite loop that hangs the program. - Confusing
repeat-while(Swift's version of do-while) with a regularwhile;repeat-whilealways executes the body at least once. - Forgetting to update the loop's controlling variable inside the body, so the condition never changes.
Chapter Summary
while condition { }checks the condition before each iteration, possibly running zero times.repeat { } while conditionchecks the condition after each iteration, always running at least once.- Both loops require the condition to eventually become false to avoid an infinite loop.
repeat-whileis Swift's equivalent ofdo-whilefound in C-family languages.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: