Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to break out of an inner For loop in Swift [duplicate]

Tags:

for-loop

swift

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

like image 905
DavidS Avatar asked Jan 24 '16 19:01

DavidS


People also ask

How do you break out of a for loop in Swift?

Swift Labeled break When using nested loops, we can terminate the outer loop with a labeled break statement.

How do you break out of the inner loop?

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.

How do you break the outer for loop from the inner 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.


2 Answers

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
            }
        }
    }
like image 151
Phil Andrews Avatar answered Oct 15 '22 07:10

Phil Andrews


There are three basic methods:

  1. Using an additional boolean flag

  2. Using a labelled loop (label: for ...) and then break label

  3. 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.

like image 29
Sulthan Avatar answered Oct 15 '22 09:10

Sulthan