Introduction
Labeled statements help you control which loop to stop or continue when you have loops inside loops.
Labeled statements help you control which loop to stop or continue when you have loops inside loops.
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.
outerLoop: for i in 1...3 { for j in 1...3 { if j == 2 { break outerLoop } print("i: \(i), j: \(j)") } }
outerLoop: for i in 1...3 { for j in 1...3 { if j == 2 { continue outerLoop } print("i: \(i), j: \(j)") } }
This program prints pairs of i and j. When both i and j are 2, it breaks the outer loop and stops all looping.
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")
Labels must be unique within the same scope.
Use labels to make your nested loops easier to control and read.
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.
outerLoop: for i in 1...2 {
for j in 1...3 {
if j == 2 {
break outerLoop
}
print("\(i),\(j)")
}
}outer: for i in 1...2 {
for j in 1...2 {
if j == 2 {
break outerLoop
}
print(i, j)
}
}Pass the test and this pattern moves unknown