Updated for Xcode 14.2
Swift’s labeled statements allow us to name certain parts of our code, and it’s most commonly used for breaking out of nested loops.
To demonstrate them, let’s look at an example where we’re trying to figure out the correct combination of movements to unlock a safe. We might start by defining an array of all possible movements:
let options = ["up", "down", "left", "right"]
For testing purposes, here’s the secret combination we’re trying to guess:
let secretCombination = ["up", "up", "right"]
To find that combination, we need to make arrays containing all possible three-color variables:
…you get the idea.
To make that happen, we can write three loops, one nested inside the other, like this:
for option1 in options {
for option2 in options {
for option3 in options {
print("In loop")
let attempt = [option1, option2, option3]
if attempt == secretCombination {
print("The combination is \(attempt)!")
}
}
}
}
That goes over the same items multiple times to create an attempt
array, and prints out a message if its attempt matches the secret combination.
But that code has a problem: as soon as we find the combination we’re done with the loops, so why do they carry on running? What we really want to say is “as soon as the combination is found, exit all the loops at once” – and that’s where labeled statements come in. They let us write this:
outerLoop: for option1 in options {
for option2 in options {
for option3 in options {
print("In loop")
let attempt = [option1, option2, option3]
if attempt == secretCombination {
print("The combination is \(attempt)!")
break outerLoop
}
}
}
}
With that small change, those three loops stop running as soon as the combination is found. In this trivial case it’s unlikely to make a performance difference, but what if your items had hundreds or even thousands of items? Saving work like this is a good idea, and worth remembering for your own code.
SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.