Updated for Xcode 15
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 Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.