Tommy Tommy - 3 months ago 7
Swift Question

How to break/escape from inner loop in Swift

I'm looking for a way to stop iterating the just inner loop once a condition is met. I thought of using "continue" but it's not doing what i wanted.
"break" seems to break the entire loop including the outer loop.

So in my code, once the condition is met. I want to stop iterating j but i want to start iterating i again. Thank you,

for i in 0..<sortedArray.count{
for j in 1..<sortedArray.count{
if sortedArray[j] == sortedArray[i]{
//I want to skip iterating inner loop j from now. and back to iterating i
}
}
}

Answer

Break just breaks the inner loop.

e.g.

for var i in 0...2
{
    for var j in 10...15
    {
        print("i = \(i) & j = \(j)")
        if j == 12
        {
            break;
        }
    }
}

Output -->

i = 0 & j = 10
i = 0 & j = 11
i = 0 & j = 12
i = 1 & j = 10
i = 1 & j = 11
i = 1 & j = 12
i = 2 & j = 10
i = 2 & j = 11
i = 2 & j = 12