FREE SAMPLE - online version

Label loop statements to control execution of nested loops

One of the lesser-known yet incredibly useful features in Swift is the concept of named loops. This feature enhances the control flow in our code, making complex loop structures more manageable and readable.

Named loops are not a separate type of loop but rather a way of labeling loop statements. In Swift, we can assign a name to loops (for, while, or repeat-while) and use this name to specifically control the flow of the program. This is particularly useful when dealing with nested loops and we need to break out of or continue an outer loop from within an inner loop.

The syntax for naming a loop is straightforward. We simply precede the loop with a label followed by a colon. Let's consider a practical example. Suppose we are working with a two-dimensional array and want to search for a specific value. Once the value is found, we'd typically want to break out of both loops. Here's how we can do it with named loops.

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]

let valueToFind = 5
searchValue: for row in matrix {
    for num in row {
        if num == valueToFind {
            print("Value \(valueToFind) found!")
            break searchValue

In this example, searchValue is the label for the outer loop. When valueToFind is found, break searchValue terminates the outer loop, preventing unnecessary iterations.

In nested loops, it's often unclear which loop the break or continue statement is affecting. Named loops remove this ambiguity, making our code more readable and maintainable.

You can read the tips online or download the sample bundle with PDF and EPUB by clicking the link below.

Download free sample

To access the remaining 10 tips in this chapter you need to purchase the book.