Swift Break, Continue and Infinite Loops — Taking Control…
    Neura MarketNeura Market/Stable Diffusion
    ChatGPTChatGPTClaudeClaudeGeminiGeminiCursorCursorGrokGrokPerplexityPerplexityStable DiffusionStable Diffusion
    DeepSeekDeepSeekCoPilotCoPilotMidjourneyMidjourney
    View All Directories
    OverviewPromptsBlogVideosGuidesCoursesCommunityModelsLoRAsComfyUI WorkflowsTrending
    Stable DiffusionBlogSwift 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
    Context bankruptcy: The case for strategic forgetting for AI Agentsai

    Context bankruptcy: The case for strategic forgetting for AI Agents

    Most of us have seen a coding agent fail to complete a task we know it can do. We just don't...

    J
    James O'Reilly
    Parallel Compliance Engine: Drive-to-Sheets Multi-Agent Orchestrationgooglecloud

    Parallel Compliance Engine: Drive-to-Sheets Multi-Agent Orchestration

    When building Generative AI applications, developers often encounter a massive bottleneck: sequential...

    A
    Aryan Irani
    Is It Ethical to Post and Ask About Circuits on Dev.to?discuss

    Is It Ethical to Post and Ask About Circuits on Dev.to?

    I’ve been thinking about sharing some electronic circuit posts on Dev.to — small circuits, DIY...

    C
    codebunny20
    The One-Click Exporter: AI Studio Antigravity, Probed to Its Limitsagents

    The One-Click Exporter: AI Studio Antigravity, Probed to Its Limits

    What nobody tells you about exporting your multi-agent prototype to a local workspace. Every...

    L
    leslysandra
    Guarding the till while autonomous data agents do the diggingagenticarchitect

    Guarding the till while autonomous data agents do the digging

    Autonomous agents are genuinely good at answering messy business questions. Give one an LLM and a set...

    S
    Sireesha Pulipati
    Return on Attention: Why AI Code Reviews Are Wearing Us Outai

    Return on Attention: Why AI Code Reviews Are Wearing Us Out

    PR volume went up, ticket quality didn't, and the gap got filled with LLMs on both sides of the review: bots reviewing, bots replying, bots occasionally arguing with bots about priorities that only existed in a teammate's head. Our CEO named the actual problem, and it's bigger than code review.

    C
    christine

    Stay up to date

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

    Neura Market LogoNeura Market

    Discover the best AI prompts, plugins, and resources for Stable Diffusion 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.

    Ready-made automations for this

    Workflows from the Neura Market marketplace related to this Stable Diffusion resource

    • Restore Your Workflows from GitHubn8n · Free · Related topic
    • Extract Business Leads from Google Maps with Dumpling AI to Google Sheetsn8n · Free · Related topic
    • Extract Text from Images & PDFs via Telegram with Mistral OCR to Markdownn8n · Free · Related topic
    • Cold Email Icebreakers from Local Business Search with GP-4 and Dumpling AIn8n · Free · Related topic
    Browse all workflows