How to Break Multiple Nested Loops in Swift

This tutorial will guide you through the process of breaking out of multiple nested loops in Swift using labeled loops.

Sometimes in Swift, you might encounter scenarios where you need to break out of multiple nested loops at once. This can be achieved by labeling your loops and then using those labels with the break statement.

Below is a step-by-step guide on how to achieve this:

Step 1: Labeling the Loops

To break out of multiple nested loops, you need to name or label each loop. You can do this by placing a label followed by a colon before the loop statement. Choose any name for your label. Here’s an example:

iLoop: for i in 1...3 {
    // ...
}

In this example, the outer loop is labeled as iLoop. The label is placed before the for keyword and is followed by the loop variable (i) and the range (1...3).

Step 2: Using the Labeled Break Statement

Once you have labeled your loops, you can use the labeled break statement to specify which loop to exit. The syntax is as follows:

break labelName

Here, labelName is the name you assigned to the loop. This statement breaks out of the loop identified by the specified label. Let’s integrate this into a more detailed example.

Example

iLoop: for i in 1...3 {
    print("i \(i)")
    jLoop: for j in 1...3 {
        print("== j \(j)")

        if j == 2 {
            // Break the outer loop (iLoop)
            break iLoop
        }
    }
}

In this example, we have an outer loop labeled as “iLoop” and an inner loop labeled as “jLoop.” The outer loop iterates over the range 1...3, and for each iteration, the inner loop iterates over the range 1...3 as well. The print statements are used for visualization.

The critical part is within the inner loop’s body: when j equals 2, we use break iLoop to break out of the outer loop labeled as “iLoop.” This means that the outer loop will stop its execution after the first iteration where the condition is met in the inner loop.

Output:

i 1
== j 1
== j 2

The outer loop stops after the first iteration because the labeled break statement exits the loop marked with “iLoop.”

By following these steps, you can break out of multiple nested loops in Swift by labeling and specifying the loop to break using the labeled break statement.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top