In Swift programming, break
and continue
statements are powerful tools for controlling the flow of loops. These statements enhance code readability and efficiency by allowing developers to skip iterations or exit loops prematurely.
The break
statement immediately terminates the execution of a loop. It's particularly useful when you want to exit a loop based on a specific condition.
for number in 1...10 {
if number == 5 {
break
}
print(number)
}
// Output: 1 2 3 4
In this example, the loop prints numbers from 1 to 4 and then exits when it reaches 5.
The continue
statement skips the rest of the current iteration and moves to the next one. It's useful when you want to skip certain elements in a loop without terminating it entirely.
for number in 1...5 {
if number % 2 == 0 {
continue
}
print(number)
}
// Output: 1 3 5
This code prints only odd numbers by skipping even numbers using the continue
statement.
break
when you need to exit a loop early based on a condition.continue
to skip specific iterations without terminating the entire loop.break
and continue
affect only the innermost loop containing them.break
and continue
in nested loops for more precise control.To further enhance your understanding of loop control in Swift, explore these related topics:
Mastering break
and continue
statements will significantly improve your ability to write efficient and readable Swift code, especially when dealing with complex loop structures.