Updated for Xcode 14.2
Swift gives us two ways to skip one or more items in a loop: continue
skips the current loop iteration, and break
skips all remaining iterations. Like while
loops these are sometimes used, but in practice much less than you might think.
Let’s look at them individually, starting with continue
. When you’re looping over an array of data, Swift will take out one item from the array and execute the loop body using it. If you call continue
inside that loop body, Swift will immediately stop executing the current loop iteration and jump to the next item in the loop, where it will carry on as normal. This is commonly used near the start of loops, where you eliminate loop variables that don’t pass a test of your choosing.
Here’s an example:
let filenames = ["me.jpg", "work.txt", "sophie.jpg", "logo.psd"]
for filename in filenames {
if filename.hasSuffix(".jpg") == false {
continue
}
print("Found picture: \(filename)")
}
That creates an array of filename strings, then loops over each one and checks to make sure it has the suffix “.jpg” – that it’s a picture. continue
is used with all the filenames failing that test, so that the rest of the loop body is skipped.
As for break
, that exits a loop immediately and skips all remaining iterations. To demonstrate this, we could write some code to calculate 10 common multiples for two numbers:
let number1 = 4
let number2 = 14
var multiples = [Int]()
for i in 1...100_000 {
if i.isMultiple(of: number1) && i.isMultiple(of: number2) {
multiples.append(i)
if multiples.count == 10 {
break
}
}
}
print(multiples)
That does quite a lot:
i
.i
is a multiple of both the first and second numbers, append it to the integer array.break
to exit the loop.So, use continue
when you want to skip the rest of the current loop iteration, and use break
when you want to skip all remaining loop iterations.
SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.