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
Asked
Active
Viewed 1.3k times
17
-
why you don't use a while loop ? – LHIOUI Jan 24 '16 at 19:38
-
additional flag is the simplest way in many languages. Sometimes there is a different solution but we would have to see the loop. – Sulthan Jan 24 '16 at 19:39
-
Also http://stackoverflow.com/questions/30768931/new-control-transfer-statements-labels-for-swift-2-0 – dawg Jan 24 '16 at 19:54
2 Answers
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:
Using an additional boolean flag
Using a labelled loop (
label: for ...
) and thenbreak label
Extracting the loops into a separate function/method and then using a
return
instead of abreak
.
From code quality perspective I believe 3. is the best solution.

Sulthan
- 128,090
- 22
- 218
- 270