How to break multiple nested loops in Swift

⋅ 1 min read ⋅ Swift

Table of Contents

In Swift, we can break for-loop using the break keyword.

By default, break will exit the loop it is executing in.

In the following example, break is in the j loop, so it would break the j loop from executing further than 2.

for i in 1...3 {
print("i \(i)")
for j in 1...3 {
print("== j \(j)")

if j == 2 {
// break j loop
break
}
}
}

j wouldn't reach the third iteration. It will print up to 2.

Here is the result.

i 1
== j 1
== j 2
i 2
== j 1
== j 2
i 3
== j 1
== j 2

You can easily support sarunw.com by checking out this sponsor.

Sponsor sarunw.com and reach thousands of iOS developers.

How to break multiple nested loops in Swift

If you want to break the outer loop from the inner one. You have to do two things.

  1. You need to name your loop.
  2. Specify the loop you want to break by its name.

Label loop statement

You can name or label your loop by putting any name you want followed by a colon.

Put it before a loop statement.

label name: for i in 1...3 {
  // ...
}

Specified the loop you want to break

Once you have a name for your loop statement, you can easily specify the loop you want to break using the following syntax.

break label name

Here is the same example, but this time, we put the label on both loop statements.

iLoop: for i in 1...3 {
print("i \(i)")
jLoop: for j in 1...3 {
print("== j \(j)")

if j == 2 {
// 1
break iLoop
}
}
}

1 We specified the loop we want to break here. In this case, iLoop, which is the outer loop.

As a result, the i loop will end at the first iteration.

i 1
== j 1
== j 2

Read more article about Swift or see all available topic

Enjoy the read?

If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.

Become a patron Buy me a coffee Tweet Share
Previous
Create Button with Rounded Corner Border in SwiftUI

Learn different ways to create a Button with a Rounded corner Border in SwiftUI.

Next
How to dismiss Keyboard in SwiftUI

Learn how to programmatically dismiss a keyboard in SwiftUI.

← Home