What if you could instantly stop all searching loops the moment you find what you want?
Why Labeled statements for nested loops in Swift? - Purpose & Use Cases
Imagine you are searching for a specific item in a big box filled with smaller boxes, and each smaller box has many compartments. You have to check every compartment one by one until you find the item.
Without a clear way to jump out of all the compartments and boxes once you find the item, you end up checking everything even after finding it. This wastes time and makes your code messy with many flags or extra checks.
Labeled statements let you name your loops so you can break out of or continue specific loops directly. This means you can stop searching immediately when you find the item, making your code cleaner and faster.
for i in 1...5 { for j in 1...5 { if condition { break } } }
outerLoop: for i in 1...5 { for j in 1...5 { if condition { break outerLoop } } }
You can control exactly which loop to exit or continue, making nested loops easier to manage and your program more efficient.
When scanning a grid for a treasure, labeled statements let you stop searching all rows and columns as soon as you find the treasure, instead of checking every cell.
Manual nested loops can be hard to control and inefficient.
Labeled statements give names to loops for precise control.
This makes breaking out of nested loops simple and clean.