break and continue
break stops a loop completely, while continue just skips the rest of the current lap and moves to the next one.
Syntax
for item in collection {
if condition { break } // leave the loop
if condition { continue } // skip to next item
}
label: for a in outer {
for b in inner { continue label }
}
Using break to Exit Early
break immediately stops the loop entirely, skipping any remaining iterations.
Example: Using break to Exit Early
// Loop over `1...10`, binding each item to `number`
for number in 1...10 {
// Check whether `number == 4`
if number == 4 {
break
}
// Print "Number: \(number)" to the console
print("Number: \(number)")
}
Login to try C/C++/Java/PHP code in the editor
Using continue to Skip an Iteration
continue skips the rest of the current iteration's code and jumps straight to the next one, without stopping the loop entirely.
Example: Using continue to Skip an Iteration
// Loop over `1...6`, binding each item to `number`
for number in 1...6 {
// Check whether `number % 2 == 0`
if number % 2 == 0 {
continue
}
// Print "Odd number: \(number)" to the console
print("Odd number: \(number)")
}
Login to try C/C++/Java/PHP code in the editor
Labeled Loops
A label placed before a loop lets break or continue target that specific loop even from inside a nested loop.
Example: Labeled Loops
outer: for i in 1...3 {
// Loop over `1...3`, binding each item to `j`
for j in 1...3 {
// Check whether `j == 2`
if j == 2 {
continue outer
}
// Print "i=\(i), j=\(j)" to the console
print("i=\(i), j=\(j)")
}
}
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
- Using
breakwhen the intent was only to skip the current iteration; that requirescontinue, notbreak. - Forgetting that
breakinside aswitchexits the switch itself, not an enclosing loop -- use a labeled break for that case. - Placing code after a
continuein the same iteration expecting it to still run; nothing aftercontinueexecutes for that pass.
Chapter Summary
breakimmediately exits the nearest enclosing loop (or switch).continueskips the rest of the current iteration and moves to the next one.- Labeled loops (
outerLoop: for ...) letbreakorcontinuetarget a specific outer loop. - Both are commonly combined with an
ifcondition to control loop flow.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: