Swift Break and Continue
When working with loops in Swift, there are times when you might want to skip certain iterations or exit a loop early. This is where the break
and continue
statements come in handy. These control transfer statements give you more precise control over the flow of your loops.
Understanding Break and Continue
Before diving into examples, let's clarify what each statement does:
break
: Immediately terminates the entire loop and transfers control to the code after the loop.continue
: Skips the current iteration of the loop and proceeds to the next iteration.
The Break Statement
The break
statement allows you to exit a loop prematurely, regardless of whether the loop condition still evaluates to true.
Basic Break Example
for number in 1...10 {
if number == 5 {
break
}
print(number)
}
print("Loop ended")
Output:
1
2
3
4
Loop ended
In this example, when number
equals 5, the break
statement executes, and the loop terminates immediately. That's why we only see numbers 1 through 4 printed.
Break with Nested Loops
In nested loops, break
only exits the innermost loop that contains it.
for i in 1...3 {
print("Outer loop: \(i)")
for j in 1...5 {
if j == 3 {
break
}
print(" Inner loop: \(j)")
}
}
Output:
Outer loop: 1
Inner loop: 1
Inner loop: 2
Outer loop: 2
Inner loop: 1
Inner loop: 2
Outer loop: 3
Inner loop: 1
Inner loop: 2
Here, the inner loop breaks when j
equals 3, but the outer loop continues running.
Real-World Example: Finding an Element
let userIDs = [1021, 1022, 1023, 1024, 1025]
let targetID = 1023
var userFound = false
for id in userIDs {
if id == targetID {
print("User \(targetID) found!")
userFound = true
break // No need to check remaining IDs
}
}
if !userFound {
print("User \(targetID) not found")
}
Output:
User 1023 found!
In this example, we're searching for a specific user ID. Once found, we use break
to exit the loop since there's no need to continue searching.
The Continue Statement
The continue
statement skips the current iteration and moves on to the next one, without exiting the entire loop.
Basic Continue Example
for number in 1...10 {
if number % 2 == 0 {
continue // Skip even numbers
}
print(number)
}
Output:
1
3
5
7
9
This example prints only odd numbers because the continue
statement skips the rest of the loop body when an even number is encountered.
Continue with Nested Loops
Like break
, the continue
statement affects only the innermost loop that contains it.
for i in 1...3 {
print("Outer: \(i)")
for j in 1...3 {
if j == 2 {
continue
}
print(" Inner: \(j)")
}
}
Output:
Outer: 1
Inner: 1
Inner: 3
Outer: 2
Inner: 1
Inner: 3
Outer: 3
Inner: 1
Inner: 3
The inner loop skips printing when j
equals 2, but it doesn't affect the outer loop.
Real-World Example: Filtering Data
let transactions = [
["id": "T1001", "amount": 120, "approved": true],
["id": "T1002", "amount": 300, "approved": false],
["id": "T1003", "amount": 550, "approved": true],
["id": "T1004", "amount": 50, "approved": true],
["id": "T1005", "amount": 800, "approved": false]
]
var totalApprovedAmount = 0
for transaction in transactions {
// Skip transactions that weren't approved
guard let isApproved = transaction["approved"] as? Bool, isApproved else {
continue
}
if let amount = transaction["amount"] as? Int {
totalApprovedAmount += amount
print("Added transaction \(transaction["id"] ?? "unknown") of $\(amount)")
}
}
print("Total amount from approved transactions: $\(totalApprovedAmount)")
Output:
Added transaction T1001 of $120
Added transaction T1003 of $550
Added transaction T1004 of $50
Total amount from approved transactions: $720
This example processes a list of transactions, using continue
to skip any transaction that wasn't approved.
Using Labels with Break and Continue
When working with nested loops, you can use labels to control which loop the break
or continue
statement applies to.
outerLoop: for i in 1...3 {
for j in 1...3 {
if i == 2 && j == 2 {
print("Breaking outer loop when i=\(i), j=\(j)")
break outerLoop
}
print("i=\(i), j=\(j)")
}
}
Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
Breaking outer loop when i=2, j=2
By labeling the outer loop as outerLoop
, we can break out of both loops at once when a specific condition is met.
Using Labels with Continue
outerLoop: for i in 1...3 {
print("Starting iteration for i=\(i)")
innerLoop: for j in 1...3 {
if i == 2 && j == 2 {
print("Continuing outer loop when i=\(i), j=\(j)")
continue outerLoop
}
print(" i=\(i), j=\(j)")
}
print("Completed inner loop for i=\(i)")
}
Output:
Starting iteration for i=1
i=1, j=1
i=1, j=2
i=1, j=3
Completed inner loop for i=1
Starting iteration for i=2
i=2, j=1
Continuing outer loop when i=2, j=2
Starting iteration for i=3
i=3, j=1
i=3, j=2
i=3, j=3
Completed inner loop for i=3
When i=2
and j=2
, we skip the rest of the inner loop and also skip the rest of the current iteration of the outer loop.
Summary
The break
and continue
statements are powerful tools for controlling loop execution in Swift:
break
terminates the loop completelycontinue
skips the current iteration and moves to the next- Both can be used with labeled statements to control which loop they affect in nested structures
Learning to use these control transfer statements effectively will help you write more efficient and readable code, especially when dealing with loops that process large sets of data.
Practice Exercises
- Write a program that prints all numbers from 1 to 20, but skips any number divisible by 3.
- Create a nested loop that generates a multiplication table for numbers 1-5, but stops the inner loop once it reaches the current outer loop number.
- Write a function that finds the first occurrence of a specific element in an array and returns its index (or nil if not found).
- Create a program that processes a list of payments, skipping any that are below a minimum threshold, and stops processing once a total payment amount is reached.
Further Reading
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)