Lesson 2
Controlling Loops with Break
Building on Basic Loops

Welcome back! Previously, we explored how to use basic for loops to iterate over collections in Swift. This foundational skill is crucial for automating repetitive tasks effectively. Now, let's take it a step further and talk about how to control those loops using a powerful keyword: break.

What You'll Learn

In this lesson, you will learn how to use the break keyword within your loops. This keyword gives you finer control over your program's flow. Specifically, you'll learn how to break out of a loop early by using break to exit a loop before it has iterated through all its elements.

Let’s dive into a practical example:

Swift
1// Checking spacecraft systems before launch 2let systems = ["engines", "navigation", "life support"] 3 4for system in systems { 5 print("Checking \(system)...") 6 7 // Assuming the navigation system fails 8 if system == "navigation" { 9 print("Navigation systems failed. Abort launch!") 10 break 11 } 12}

We'll review each part of this code in detail during the lesson.

Why It Matters

Using break allows you to write more flexible and efficient loops. Imagine you're checking multiple systems on a spacecraft. If one system fails, you might want to stop all checks immediately (break). This tool helps you control the flow of your loops more precisely, making your code more robust and easier to manage.

Ready to see this concept in action? Let's move on to the practice section and put what you've learned to the test.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.