17

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

DavidS
  • 520
  • 1
  • 4
  • 13

2 Answers2

34

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
            }
        }
    }
Max Phillips
  • 6,991
  • 9
  • 44
  • 71
  • Great answer! I had a loop(3) inside a loop(2) inside a dictionary loop(1) and once I found the value in (3) I was able to easily stop the dictionary loop (1). Thanks – Lance Samaria May 09 '19 at 19:44
22

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.

Sulthan
  • 128,090
  • 22
  • 218
  • 270