0
0
Swiftprogramming~3 mins

Why Break and continue behavior in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could instantly skip what you don't want and stop as soon as you find what you need?

The Scenario

Imagine you are sorting through a long list of emails to find the first one from your best friend or skipping all spam messages manually.

The Problem

Going one by one without a quick way to stop or skip wastes time and can cause mistakes, like missing the important email or reading spam unnecessarily.

The Solution

Using break lets you stop searching as soon as you find what you want, and continue lets you skip unwanted items quickly, making your code faster and cleaner.

Before vs After
Before
for email in emails {
    if email.isSpam {
        // no easy way to skip, must check everything
    }
    if email.sender == "bestFriend" {
        print("Found it")
        // no easy way to stop loop
    }
}
After
for email in emails {
    if email.isSpam {
        continue
    }
    if email.sender == "bestFriend" {
        print("Found it")
        break
    }
}
What It Enables

You can control loops precisely to skip or stop tasks exactly when needed, saving time and effort.

Real Life Example

When scanning a list of products, you can skip all out-of-stock items and stop searching once you find the first product on sale.

Key Takeaways

Break stops the loop immediately when a condition is met.

Continue skips the current item and moves to the next one.

Both help write cleaner, faster, and more efficient loops.