0
0
Swiftprogramming~5 mins

Break and continue behavior in Swift

Choose your learning style9 modes available
Introduction

Break and continue help control loops by stopping or skipping parts of the loop. They make your code easier to manage.

Stop a loop early when you find what you need, like searching for a name in a list.
Skip certain items in a loop, like ignoring empty strings when processing text.
Exit a loop when an error happens to avoid wrong results.
Skip processing for some numbers, like ignoring even numbers when counting odds.
Syntax
Swift
for item in collection {
    if conditionToStop {
        break
    }
    if conditionToSkip {
        continue
    }
    // other code
}

break stops the whole loop immediately.

continue skips the rest of the current loop cycle and moves to the next one.

Examples
This loop prints numbers until it reaches 3, then stops completely.
Swift
for number in 1...5 {
    if number == 3 {
        break
    }
    print(number)
}
This loop skips printing 3 but continues printing other numbers.
Swift
for number in 1...5 {
    if number == 3 {
        continue
    }
    print(number)
}
Sample Program

This program loops through numbers 1 to 5. It skips even numbers and stops completely when it finds 4.

Swift
let numbers = [1, 2, 3, 4, 5]

for number in numbers {
    if number == 4 {
        print("Found 4, stopping loop.")
        break
    }
    if number % 2 == 0 {
        print("Skipping even number: \(number)")
        continue
    }
    print("Processing number: \(number)")
}
OutputSuccess
Important Notes

Use break to exit loops early when you no longer need to continue.

Use continue to skip only the current loop cycle but keep looping.

Both help make loops more efficient and easier to read.

Summary

break stops the entire loop immediately.

continue skips the rest of the current loop cycle and moves to the next.

Use them to control loop flow clearly and simply.