DEV Community

Gamya
Gamya

Posted on

Swift Break, Continue and Infinite Loops โ€” Taking Control of Your Loops ๐ŸŽฎ

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)")
}
Enter fullscreen mode Exit fullscreen mode

Output:

Found image: naruto.jpg
Found image: sasuke.jpg
Enter fullscreen mode Exit fullscreen mode

Breaking it down:

  • Loop goes through each filename one by one
  • If the file is not a .jpg โ†’ continue skips it and moves to the next
  • If the file is a .jpg โ†’ the print runs
  • notes.txt and jutsu.psd are 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.")
Enter fullscreen mode Exit fullscreen mode

Output:

You scored 4 times before getting 0.
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

[28, 56, 84, 112, 140, 168, 196, 224, 252, 280]
Enter fullscreen mode Exit fullscreen mode

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_000 is 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!")
Enter fullscreen mode Exit fullscreen mode

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:

  1. Check for any user input
  2. Run any code needed
  3. Redraw the screen
  4. 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!")
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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!
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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!
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Found it: ["up", "up", "right"]! ๐Ÿ”“
Enter fullscreen mode Exit fullscreen mode

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!")
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

๐ŸŒŸ 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 break out of multiple nested loops at once with break 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)

Collapse
 
junhao profile image
Jun Hao

โค๏ธโค๏ธโค๏ธMY DEAR GAMYA.โค๏ธโค๏ธโค๏ธ

๐ŸŒŸ Absolutely wonderful article! ๐ŸŒŸ

This is one of the clearest and most beginner-friendly explanations of loops, continue, and break that 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 continue and break using 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! ๐Ÿš€๐ŸŽ๐Ÿ‘

Collapse
 
gamya_m profile image
Gamya

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! ๐ŸŒธ๐Ÿš€

Collapse
 
junhao profile image
Jun Hao

ThankDear Gamya.

Thank you for your message

I want you are doing well

best regards.