Blog / May 23, 2022 / 2 mins read / By Mahi Garg

Labeled Statement : Swift

Swift has a few inbuilt features which make our life super easy. Labeled statements are one of them. It allows us to name a statement and later within the scope, that particular statement can be referenced using the label provided.

Let me explain this using an example. Assume we have a nested loop inside another loop. We want to break the inner as well as out loop on some condition.

for i in 0...5 {
     for j in 0...5 {
        print (i + j)
        
        //break from outer loop if i + j == 5
    }
}

Break statement can help here but break statement only works for immediate loop.

for i in 0...5 {
    for j in 0...5 {
        print (i + j)
        
        //break from outer loop if i + j == 5
        if (i + j == 5) {
            break
        }
    }
}

It will just break the inner loop but not the outer loop.

There is one way where we can use a boolean flag and set it to true when we found the first condition true and every time we check inside the outer loop for that flag.

There is another way where we can move this to a function and return from the function when the first time condition met.

But there is a simpler way in swift which can help us here. we can name the loops as per the requirement and can break them using the name of the loop as below.

outerLoop: for i in 0...5 {
    innerLoop: for j in 0...5 {
        print (i + j)
        
        //break from outer loop if i + j == 5
        if (i + j == 5) {
            break outerLoop
        }
    }
}

We can skip the label if we are not going to use it inside.

These label statement can be used with if statement, for-loop, while-loop, repeat and switch statement which makes our life super easy.

Comments