Break outer loop in Swift
2 min readJun 4, 2022
Many times we have to use multiple loops in our project like below: -
for i in 1...10 { print ("loop 1 at \(i)") for j in 1...5 { if i == 5 { break } print ("loop 2 at \(j)") }}
Now case is that I want to break outer loop when my condition got satisfied
But here Labeled Statements can help us in this case like below: -
outerLoop: for i in 1...10 { // We provided a name to loop here print ("loop 1 at \(i)") for j in 1...5 { if i == 5 { break outerLoop // We break specific loop here } print ("loop 2 at \(j)") }}
we added a label to the outer loop so we can break out of both loops at once.
So this is the best way to handle multiple loops in Swift, and we can able to break or continue the correct loop.
Note: We can give any name to outer loop
For more visit: https://ioslifee.blogspot.com
Thanks for reading, Happy Coding 💻