So far our loops have run from start to finish without interruption. But sometimes you need more control ā skip certain items, stop early when you've found what you need, or break out of multiple nested loops at once.
That's exactly what continue, break, and infinite loops are for. š§
āļø continue ā Skip This Item, Keep Going
continue tells Swift to stop the current iteration and jump straight to the next one. Everything after continue in the loop body gets skipped ā but the loop itself keeps running.
Think of it like this:
You're going through your playlist and skipping songs you don't like ā you skip that one song but keep listening to the rest. šµ
Here's a practical example ā filtering only image files from a list:
let filenames = ["naruto.jpg", "notes.txt", "sasuke.jpg", "jutsu.psd"]
for filename in filenames {
if filename.hasSuffix(".jpg") == false {
continue
}
print("Found image: \(filename)")
}
Output:
Found image: naruto.jpg
Found image: sasuke.jpg
Breaking it down:
- Loop goes through each filename one by one
- If the file is not a
.jpgācontinueskips it and moves to the next - If the file is a
.jpgā the print runs -
notes.txtandjutsu.psdare skipped entirely
š break ā Stop the Loop Completely
break tells Swift to exit the loop immediately ā no more iterations, no more items. The loop is done.
Think of it like this:
You're searching through your bag for your keys ā the moment you find them you stop searching. No point checking the rest of the bag! š
Here's a real example ā finding how many scores a player got before hitting 0:
let scores = [8, 5, 3, 4, 0, 6, 2]
var count = 0
for score in scores {
if score == 0 {
break
}
count += 1
}
print("You scored \(count) times before getting 0.")
Output:
You scored 4 times before getting 0.
The moment we hit 0 in the array, break fires and the loop stops. We never even look at the 6 and 2 after it ā no point checking what comes after a 0! ā
š¢ break with a Range ā Finding Common Multiples
Here's a more advanced example ā finding the first 10 common multiples of two numbers:
let number1 = 4
let number2 = 14
var multiples = [Int]()
for i in 1...100_000 {
if i.isMultiple(of: number1) && i.isMultiple(of: number2) {
multiples.append(i)
if multiples.count == 10 {
break
}
}
}
print(multiples)
Output:
[28, 56, 84, 112, 140, 168, 196, 224, 252, 280]
What's happening:
- We loop through 1 to 100,000
- Every time we find a number that's a multiple of both 4 and 14 we add it to the array
- The moment we have 10 multiples we call
breakā no point checking the remaining 99,720 numbers! -
100_000is just Swift's way of writing 100000 ā the underscore makes big numbers easier to read š
š continue vs break ā The Key Difference
This is the part that confuses most beginners ā here's the clearest way to think about it:
| Keyword | What it does | Loop continues? |
|---|---|---|
continue |
Skip the rest of this iteration | ā Yes ā moves to next item |
break |
Skip all remaining iterations | ā No ā exits completely |
Imagine you're a bouncer at a club checking IDs:
-
continueā "You're under 18, skip you, next person please!" ā keeps checking others šŖ -
breakā "Club is full, everyone go home!" ā stops checking entirely š
ā¾ļø Infinite Loops ā Running Forever on Purpose
Now here's something that might surprise you ā sometimes you actually want a loop to run forever. These are called infinite loops.
while true {
print("I'm alive!")
}
print("I've snuffed it!")
In this code "I'm alive!" prints forever ā and "I've snuffed it!" never prints because the loop never ends.
You might be thinking ā "when would I ever want that?" ā but actually infinite loops are incredibly common in real apps!
š± Every App You Use Has an Infinite Loop
Think about what happens when you open an app on your iPhone. It needs to keep running a cycle over and over:
- Check for any user input
- Run any code needed
- Redraw the screen
- Repeat ā¾ļø
This keeps going for as long as you have the app open ā whether that's 10 seconds or 3 hours. The app has no idea upfront how long you'll use it, so it can't use a regular loop with a fixed number. It just keeps going until you close it.
š Pseudo-Infinite Loops
In practice you'll rarely write while true directly. Instead you'll use a condition that could become false ā making it what programmers call a pseudo-infinite loop:
var isAlive = true
while isAlive {
print("Still running...")
// somewhere in here, isAlive might become false
}
print("Loop ended!")
It runs for a long time ā maybe forever in systems that never restart ā but technically it can be stopped. This is exactly how game loops, server processes, and app lifecycles work in the real world. š
š·ļø Labeled Statements ā Breaking Out of Nested Loops
Here's a situation that trips people up. What happens when you have loops inside loops and you want to break out of all of them at once?
Regular break only exits the innermost loop ā the outer loops keep running. That's where labeled statements come in.
Let's say we're trying to crack a safe combination:
let options = ["up", "down", "left", "right"]
let secretCombination = ["up", "up", "right"]
Without labeled statements ā the loops keep running even after finding the answer:
for option1 in options {
for option2 in options {
for option3 in options {
let attempt = [option1, option2, option3]
if attempt == secretCombination {
print("Found it: \(attempt)!")
break // ā ļø only breaks the innermost loop!
}
}
}
}
The break here only exits the third loop ā the first and second loops keep going and keep trying combinations even though we already found the answer. That's wasted work! š¬
ā The Fix ā Labeled Statements
Add a label to the outer loop and use it with break:
outerLoop: for option1 in options {
for option2 in options {
for option3 in options {
let attempt = [option1, option2, option3]
if attempt == secretCombination {
print("Found it: \(attempt)! š")
break outerLoop // exits ALL three loops at once!
}
}
}
}
Output:
Found it: ["up", "up", "right"]! š
Now the moment we find the combination, break outerLoop exits all three loops instantly. No more wasted iterations! ā”
š§© Putting It All Together
Here's a mini example combining everything we covered:
// continue ā only train with elite ninja
let ninja = ["Naruto", "Rookie", "Sasuke", "Rookie", "Kakashi"]
print("Elite training squad:")
for member in ninja {
if member == "Rookie" {
continue // skip rookies
}
print("ā \(member)")
}
// break ā stop searching once target is found
let targets = ["Orochimaru", "Itachi", "Kisame", "Pain"]
var found = ""
for target in targets {
if target == "Itachi" {
found = target
break // no need to keep searching
}
}
print("\nTarget found: \(found)! šÆ")
// labeled break ā escape a nested search
let floors = ["B1", "B2", "B3"]
let rooms = ["Room1", "Room2", "Room3"]
let secretRoom = ("B2", "Room2")
print("\nSearching for secret room...")
floorLoop: for floor in floors {
for room in rooms {
if floor == secretRoom.0 && room == secretRoom.1 {
print("Found secret room at \(floor) - \(room)! šŖ")
break floorLoop
}
}
}
// pseudo-infinite loop ā runs until condition changes
var isSearching = true
var attempts = 0
while isSearching {
attempts += 1
if attempts == 5 {
isSearching = false
}
}
print("\nSearch completed after \(attempts) attempts!")
Output:
Elite training squad:
ā Naruto
ā Sasuke
ā Kakashi
Target found: Itachi! šÆ
Searching for secret room...
Found secret room at B2 - Room2! šŖ
Search completed after 5 attempts!
š Wrap Up
-
continueā skips the rest of the current iteration and moves to the next item -
breakā exits the entire loop immediately, skipping all remaining items - Infinite loops ā loops that run forever, used in every real app for things like game loops and app lifecycles
- Pseudo-infinite loops ā loops that run until a condition changes, the more common real-world version
-
Labeled statements ā let you
breakout of multiple nested loops at once withbreak labelName
Use continue when you want to filter items, break when you've found what you need, and infinite loops when your code needs to keep running until told to stop ā just like every app on your phone does! šŖ
Next up we'll look at functions ā one of the most important building blocks in Swift. See you there! š

