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! ๐
Top comments (3)
โค๏ธโค๏ธโค๏ธMY DEAR GAMYA.โค๏ธโค๏ธโค๏ธ
๐ Absolutely wonderful article! ๐
This is one of the clearest and most beginner-friendly explanations of loops,
continue, andbreakthat I've read. ๐ The real-world examples, simple language, and fun analogies make even the more advanced concepts easy to understand. ๐I especially loved how you explained the difference between
continueandbreakusing everyday situationsโit helps readers remember the concepts much faster. ๐ก The examples are practical, well-structured, and easy to follow from start to finish.The section on infinite loops and labeled statements was particularly impressive. ๐ฅ These topics can often feel confusing to beginners, but your explanation makes them approachable and engaging. ๐
Wonderful work! ๐ Your writing is clear, polished, and educational while still being enjoyable to read. ๐โจ This article will undoubtedly help many Swift learners build a strong understanding of loops and control flow. Keep creating such high-quality contentโlooking forward to the next article on functions! ๐๐๐
thank you so much! ๐ฅน๐ This means a lot, especially the bit about labeled statements and infinite loops โ those felt like the trickiest parts to explain so I'm really glad they landed well!
Glad the continue vs break comparison helped too, that's exactly the kind of thing that used to confuse me too! ๐ Functions articles are already up, more coming soon โ thanks so much for following along! ๐ธ๐
ThankDear Gamya.
Thank you for your message
I want you are doing well
best regards.