Understanding Break Statement
The break statement in Swift is a powerful control flow tool used to terminate loops or switch statements before their natural conclusion. This feature enhances the efficiency and flexibility of your code by stopping execution at a specified condition.
How the break Statement Works
The following diagram represents the workflow of the break statement:
- The loop or switch case starts execution.
- Upon meeting the break condition, the execution halts immediately.
- The program continues running the next line of code after the loop or switch block.
Using break in Loops
The break statement is frequently used within loops to terminate execution when a specific condition is met.
Example 1: Using break in a for-in Loop
import
Foundation
print("Counting up to 5, but stopping at 3:")
for number in
1...5 {
if number ==
3 {
print("Stopping at \(number) ")
break
}
print(number)
}
Output
1
2
Stopping at 3
Example 2: break in a Nested Loop
import
Foundation
for outer in
1...3 {
for inner in
1...5 {
if inner ==
4 {
print("Breaking inner loop at (\(outer),
\(inner))")
break
}
print("(\(outer),
\(inner))")
}
}
Output
(1, 2)
(1, 3)
Breaking inner loop at (1, 4)
(2, 1)
(2, 2)
(2, 3)
Breaking inner loop at (2, 4)
(3, 1)
(3, 2)
(3, 3)
Breaking inner loop at (3, 4)
Example 3: Using break in a while Loop
The break statement can also be used in a while loop to stop execution based on a dynamic condition.
import
Foundation
var count = 1
while true {
print("Iteration: \(count)")
if count == 5 {
print("Loop exits at count = \(count)")
break
}
count += 1
}
Output
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
Loop exits at count = 5
Using break in a switch Statement
Swift’s switch statements do not fall through by default, unlike some other languages. However, using break explicitly can help terminate a case block early.
Example 4: break in a switch Statement
import
Foundation
let season = "Winter"
switch season {
case "Spring", "Summer" :
print("It's a warm season!")
case "Autumn", "Winter":
print("Cold season detected!")
break
default:
print("Invalid season")
}