Chapter 62: Swift Break/Continue
1. What are break and continue?
Both break and continue are control transfer statements — they change the normal flow of a loop.
| Keyword | What it does in a loop | Analogy (very clear) | Effect on outer loops (when nested) |
|---|---|---|---|
| break | Immediately exits the nearest loop (stops completely) | “I’m done here — I’m leaving the room right now” | Only exits the innermost loop |
| continue | Immediately skips to the next iteration (jumps to the next loop cycle) | “Skip this person — go to the next one in line” | Only affects the innermost loop |
Both only work inside loops (for, while, repeat … while) and inside switch statements (but today we focus on loops).
2. break – exit the loop early
Most common use case: You are looking for one thing — as soon as you find it → stop searching.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
let numbers = [7, 14, 23, 42, 19, 56, 88] var found = false var position = -1 for (index, number) in numbers.enumerated() { if number == 42 { found = true position = index break // ← stop immediately — no need to check the rest } } if found { print("Found 42 at position \(position + 1)") } else { print("42 not found") } |
Real-life analogy:
Imagine you are searching for your car keys in a messy room. As soon as you find them → you stop searching (you break out of the loop).
Real app example – find first error in list
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
let validationResults = [ "Email is valid", "Password is strong", "Age is okay", "Username already taken", // ← error here "Terms accepted" ] var firstError: String? = nil for message in validationResults { if message.contains("taken") || message.contains("invalid") { firstError = message break } } if let error = firstError { print("Cannot proceed: \(error)") } else { print("All validations passed") } |
3. continue – skip the rest of this iteration
Most common use case: You want to ignore certain items and continue with the next ones.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print("Even numbers only:") for number in numbers { if number % 2 != 0 { continue // ← skip this number completely, go to next iteration } print(number) } |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 11 |
Even numbers only: 2 4 6 8 10 |
Real-life analogy:
You are checking a list of job applicants. When you see someone without experience → you skip them (continue) and look at the next candidate.
Real app example – skip inactive users
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
let users = [ (name: "Rahul", isActive: true, score: 920), (name: "Priya", isActive: false, score: 980), (name: "Aarav", isActive: true, score: 850), (name: "Sneha", isActive: true, score: 950) ] print("Active users leaderboard:") for user in users { if !user.isActive { continue // skip inactive users } print("• \(user.name) - \(user.score) points") } |
4. Combining break & continue – very realistic patterns
Pattern 1 – Find first valid item (break early)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
let files = ["photo.jpg", "document.pdf", "image.png", "virus.exe", "picture.jpeg"] var firstImage: String? = nil for file in files { if file.hasSuffix(".exe") || file.hasSuffix(".bat") { print("Skipping suspicious file: \(file)") continue } if file.hasSuffix(".jpg") || file.hasSuffix(".png") || file.hasSuffix(".jpeg") { firstImage = file break // found one → no need to check more } } if let image = firstImage { print("First safe image: \(image)") } else { print("No images found") } |
Pattern 2 – Process only valid items (continue skips)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
let transactions = [1200, -450, 3000, -9999, 1500, 0, 2500] var totalIncome = 0 for amount in transactions { if amount <= 0 { continue // skip expenses & zero } totalIncome += amount print("Added income: ₹\(amount) → current total: ₹\(totalIncome)") } |
5. Nested loops with break & continue (very important)
When you have nested loops, break and continue affect only the innermost loop.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
outer: for i in 1...4 { print("Outer loop: \(i)") for j in 1...5 { if j == 3 { print(" → skipping inner j=3 with continue") continue // only skips this j — continues with next j } if j == 5 { print(" → breaking inner loop at j=5") break // exits inner loop — goes to next outer iteration } print(" Inner: i=\(i), j=\(j)") } } |
Output (simplified):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Outer loop: 1 Inner: i=1, j=1 Inner: i=1, j=2 → skipping inner j=3 with continue Inner: i=1, j=4 → breaking inner loop at j=5 Outer loop: 2 ... |
How to break out of outer loop? Use labeled break (rare but very useful):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
outerLoop: for i in 1...4 { for j in 1...5 { if i == 2 && j == 4 { print("Breaking out of both loops!") break outerLoop // ← exits BOTH loops } print("i=\(i), j=\(j)") } } |
6. Very Common Beginner Mistakes & Fixes
| Mistake | Wrong / Dangerous code | Correct / Better habit | Why? |
|---|---|---|---|
| Forgetting to update loop variable | while count > 0 { print(count) } | count -= 1 inside loop | Infinite loop |
| Using break / continue outside loop | break outside any loop | Only inside for, while, repeat, switch | Compile error |
| Expecting break to exit outer loop | break inside inner loop | Use break outerLabel: | break only exits innermost loop |
| Using continue in forEach | array.forEach { if … continue } | Use for-in instead | forEach does not support continue |
| No safety limit in while true | while true { … } without break | Add counter + if attempt > max { break } | Prevents infinite loop |
7. Quick Summary – break vs continue
| Keyword | Effect inside loop | Typical real-life sentence | Can exit outer loop? |
|---|---|---|---|
| break | Exit the loop completely — go after the loop | “Found it — stop searching now” | Yes (with label) |
| continue | Skip the rest of this iteration — go to next one | “This item is invalid — skip to the next one” | No |
8. Small Practice – Try these
- Create array of 10 numbers → Use for + continue to print only even numbers → Use break to stop after finding the first number > 50
- Create array of 8 words → Print only words longer than 4 letters → Stop completely if you find the word “stop”
- Create 2D array (3×4) of numbers → Use nested for → continue if number is negative → break inner loop if you find number > 100
Paste your code here if you want feedback or want to see more elegant versions!
What would you like to explore next?
- break & continue with labeled loops (nested exit)
- forEach vs for-in vs map vs filter
- Loops in SwiftUI (ForEach vs manual while)
- while let pattern (very common with optionals)
- Or move to another topic (switch, functions, arrays, optionals…)
Just tell me — we’ll continue in the same clear, patient, detailed style 😊
