Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break outer loops from inner structures that respond break (loops/switch)

How to I break an outer loop from within an nested structure that responds to the break statement in Swift?

For example:

while someCondition {     if someOtherCondition {         switch (someValue) {             case 0:     // do something             case 1:     // exit loop             case 2...5: // do something else             default:    break         }     } else {         someCondition = false     } } 

The break will only get me out of the switch, and in Swift, it has to be used as empty cases are not allowed. How can I entirely exit the loop from within the switch?

like image 346
nhgrif Avatar asked Jun 05 '14 00:06

nhgrif


People also ask

How do you break the outer loop if the inner loop breaks?

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.

Does Break Break outer loop?

Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

How do you break outer loops in Swift?

Breaking the loop Placing the break clause in the inner loop answers the question: It breaks the inner loop, and returns control back to the outer loop (which continues). If you want to specify the outer loop you need to name the loop, and break that instead.


1 Answers

Swift allows for labeled statements. Using a labeled statement, you can specify which which control structure you want to break from no matter how deeply you nest your loops (although, generally, less nesting is better from a readability standpoint). This also works for continue.

Example:

outerLoop: while someCondition {     if someOtherCondition {         switch (someValue) {             case 0:     // do something             case 1:     break outerLoop // exit loop             case 2...5: // do something else             default:    break         }     } else {         someCondition = false     } } 
like image 111
nhgrif Avatar answered Oct 03 '22 10:10

nhgrif