Use Labeled Statements in Swift
Written by Team Kodeco
A labeled statement is a statement that is assigned a label, which can then be used to control the flow of execution of nested loops and conditional statements. This is typically used with a break
or continue
statement to specify which loop or conditional statement to exit or continue.
Here’s an example of using a labeled statement to exit a nested loop:
outerloop: for i in 1...3 {
for j in 1...3 {
if i == 2 && j == 2 {
// exit the outer loop when i is equal to 2 and j is equal to 2
continue outerloop
}
print("i: \(i), j: \(j)")
}
}
// Output: i: 1, j: 1
// i: 1, j: 2
// i: 1, j: 3
// i: 2, j: 1
// i: 3, j: 1
// i: 3, j: 2
// i: 3, j: 3
In this example, the outer loop iterates through the range 1…3, and the inner loop also iterates through the range 1…3.
When the values of i
and j
are both equal to 2, the continue
statement is executed, which continues to the next iteration of outerloop
, where i
is now 3.
This effectively skips the printing of (2, 2) and (2, 3) in this example.