UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Why does Swift have labeled statements?

Paul Hudson    @twostraws   

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:

  • up, up, up
  • up, up, down
  • up, up, left
  • up, up, right
  • up, down, left
  • up, down, right

…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.

Hacking with Swift is sponsored by RevenueCat

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.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.8/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.