Swift Break & Continue

Swift Break and Continue

Sometimes you need to alter the flow of a loop from within its code block.

Swift provides control transfer statements like break and continue to help you manage this.

These keywords give you precision control over when loops should skip an iteration or terminate entirely.


The break Statement

The break statement immediately ends the execution of an entire loop.

As soon as Swift hits break, it jumps out of the loop and moves to the next line of code outside the loop's body.

Break Example:

for i in 1...10 {
    if i == 5 {
        print("Hit number 5, breaking the loop!")
        break
    }
    print(i)
}
// Output: 1, 2, 3, 4, Hit number 5...

The continue Statement

The continue statement stops the current iteration of the loop and tells Swift to jump back to the top and begin the next iteration.

It skips the remaining code in the loop body for that pass only.

Continue Example:

for i in 1...5 {
    if i == 3 {
        continue // Skips printing 3
    }
    print(i)
}
// Output: 1, 2, 4, 5

Using with While Loops

Both break and continue work identically within while and repeat-while loops.

When writing an infinite while true loop, a break statement is strictly required to eventually terminate the program!

Break in a While Loop:

var count = 0
while true {
    count += 1
    if count >= 3 { break }
}

Exercise

Which keyword is used to skip the rest of the current loop iteration and move to the next one?