0
0
Swiftprogramming~5 mins

Labeled statements for nested loops in Swift

Choose your learning style9 modes available
Introduction

Labeled statements help you control which loop to stop or continue when you have loops inside loops.

When you want to exit an outer loop from inside an inner loop.
When you want to skip to the next iteration of an outer loop from inside an inner loop.
When you have multiple loops and need clear control over which one to break or continue.
When you want to avoid extra flags or complicated conditions to control nested loops.
Syntax
Swift
outerLabel: for item in collection {
    for innerItem in anotherCollection {
        if condition {
            break outerLabel
        }
    }
}

The label is a name followed by a colon before the loop.

You use break label or continue label to control the labeled loop.

Examples
This stops both loops when j equals 2 by breaking the outer loop.
Swift
outerLoop: for i in 1...3 {
    for j in 1...3 {
        if j == 2 {
            break outerLoop
        }
        print("i: \(i), j: \(j)")
    }
}
This skips to the next iteration of the outer loop when j equals 2.
Swift
outerLoop: for i in 1...3 {
    for j in 1...3 {
        if j == 2 {
            continue outerLoop
        }
        print("i: \(i), j: \(j)")
    }
}
Sample Program

This program prints pairs of i and j. When both i and j are 2, it breaks the outer loop and stops all looping.

Swift
outerLoop: for i in 1...3 {
    for j in 1...3 {
        if i == 2 && j == 2 {
            print("Breaking outer loop at i=2, j=2")
            break outerLoop
        }
        print("i: \(i), j: \(j)")
    }
}
print("Done")
OutputSuccess
Important Notes

Labels must be unique within the same scope.

Use labels to make your nested loops easier to control and read.

Summary

Labeled statements let you name loops to control them directly.

You can break or continue outer loops from inside inner loops using labels.

This helps avoid complicated flags or conditions in nested loops.