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:
Syntax
while condition {
// body
}
repeat {
// body runs at least once
} while condition
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
// Declare a mutable variable `countdown`, initialized to `3`
var countdown = 3
// Keep looping while `countdown > 0` holds
while countdown > 0 {
// Print "T-minus \(countdown)" to the console
print("T-minus \(countdown)")
countdown -= 1
}
// Print "Liftoff!" to the console
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
// Declare a mutable variable `attempts`, initialized to `0`
var attempts = 0
repeat {
attempts += 1
// Print "Attempt number \(attempts)" to the console
print("Attempt number \(attempts)")
} while attempts < 3
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: