Swift Break, Continue and Infinite Loops — Taking Control…
    Neura MarketNeura Market/Midjourney
    ChatGPTChatGPTClaudeClaudeGeminiGeminiCursorCursorGrokGrokPerplexityPerplexityMidjourneyMidjourney
    DeepSeekDeepSeekCoPilotCoPilotStable DiffusionStable Diffusion
    View All Directories
    OverviewPromptsBlogVideosGuidesCoursesCommunityStylesTrending
    MidjourneyBlogSwift Break, Continue and Infinite Loops — Taking Control of Your Loops 🎮
    Back to Blog
    Swift Break, Continue and Infinite Loops — Taking Control of Your Loops 🎮
    programming

    Swift Break, Continue and Infinite Loops — Taking Control of Your Loops 🎮

    Gamya June 9, 2026
    0 views

    So far our loops have run from start to finish without interruption. But sometimes you need more...

    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 → 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.")
    

    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_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:

    KeywordWhat it doesLoop continues?
    continueSkip the rest of this iteration✅ Yes — moves to next item
    breakSkip 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:

    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!")
    

    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 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! 👋

    Tags

    programmingswiftswiftuiios

    Comments

    More Blog

    View all
    Five Gemma-4 models, one accelerator: what porting E2B 31B to AWS Inferentia2 taught megemma

    Five Gemma-4 models, one accelerator: what porting E2B 31B to AWS Inferentia2 taught me

    I ported the whole Gemma-4 family — E2B, E4B, 12B, 31B, and the 26B-A4B MoE — to run on...

    X
    xbill
    Hey DEV, I'm Tobore. Let's actually connect.community

    Hey DEV, I'm Tobore. Let's actually connect.

    Hey DEV, I'm Tobore. Let's actually connect. I've been on here for a while now, mostly writing and...

    L
    Laurina Ayarah
    I burned through thousands of AI tokens. Then a friend did it for freeai

    I burned through thousands of AI tokens. Then a friend did it for free

    (yep, kinda clickbait, just for the funsies 😊) At the beginning of the year, I relaunched my...

    P
    Paulo Henrique
    Claude might be saturating your machineai

    Claude might be saturating your machine

    My laptop was sitting idle with the fan at full tilt. Nothing was running that I knew of. The culprit...

    S
    Sidhant Panda
    Automated GitHub Code Reviews Using Google Geminigithubactions

    Automated GitHub Code Reviews Using Google Gemini

    I Built a Thing! TL;DR — Google Gemini-based Pull Request reviews and Issue Triaging for...

    D
    Darren "Dazbo" Lester
    What is an "agentic harness," actually?ai

    What is an "agentic harness," actually?

    I've been hearing the word "harness" thrown around a lot lately. I assumed it just meant "the IDE" or...

    T
    Tilde A. Thurium

    Stay up to date

    Get the latest Midjourney prompts, rules, and resources delivered to your inbox weekly.

    Neura Market LogoNeura Market

    Discover the best AI prompts, plugins, and resources for Midjourney and more.

    Content Types

    • Rules
    • Prompts
    • MCPs
    • Agents
    • Guides

    Platforms

    • ChatGPT Directory
    • Claude Directory
    • Gemini Directory
    • Cursor Directory
    • Grok Directory
    • Perplexity Directory
    • DeepSeek Directory
    • CoPilot Directory
    • Stable Diffusion Directory
    • Midjourney Directory
    • All Directories

    Resources

    • Blog
    • Documentation
    • Help Center
    • Marketplace

    Legal

    • Privacy Policy
    • Terms of Service

    © 2026 Neura Market. All rights reserved.

    |

    Not affiliated with any AI platform vendors.

    Neura Market

    Custom AI Systems & Services

    Our team of experienced AI builders will help build custom AI systems, workflows, and solutions for your business.

    Request custom work

    Ready-made automations for this

    Workflows from the Neura Market marketplace related to this Midjourney resource

    • Automate Your Creative Process with Midjourney and GPT-4 Image APIn8n · $8.22 · Related topic
    • Create Animated Stories Using GP-4.0-mini, Midjourney, Kling, and Creatomate APIn8n · $24.99 · Related topic
    • Extract Text from Images & PDFs via Telegram with Mistral OCR to Markdownn8n · $24.99 · Related topic
    • Write a WordPress Post with AI (Starting from a Few Keywords)n8n · $24.99 · Related topic
    Browse all workflows