Is there a simple way to break out of an inner For loop, i.e. a Fro loop within another For loop? Without having to set additional flags for example
Swift Labeled break When using nested loops, we can terminate the outer loop with a labeled break statement.
There are two steps to break from a nested loop, the first part is labeling loop and the second part is using labeled break. You must put your label before the loop and you need a colon after the label as well. When you use that label after the break, control will jump outside of the labeled loop.
Java break and Nested Loop In the case of nested loops, the break statement terminates the innermost loop. Here, the break statement terminates the innermost while loop, and control jumps to the outer loop.
You just need to name your loop. Like this:
let array = [1,2,3]
for number in 1...6 {
innerLoop: for i in array {
let newNumber = i + number
if i == 2 {
break innerLoop
}
}
}
There are three basic methods:
Using an additional boolean flag
Using a labelled loop (label: for ...
) and then break label
Extracting the loops into a separate function/method and then using a return
instead of a break
.
From code quality perspective I believe 3. is the best solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With