Topics

#205: Swift guard Basics ⚔

Topics

The guard statement was added to Swift in its 2.0 release. It can dramatically increase the readability and clarity of the conditional checks in our code.

It supports Swift's inline optional unwrapping as well as pattern matching. Let's try it out!

We can think of the guard statement like a sort of inverted if statement. We essentially say: "this thing must be true otherwise we're bailing out!". Here's a fairly full-featured example:

func launch() {
  guard let fc = fuelCell where fc.level > 0.5 else {
    showLowFuelWarning()
    return
  }

  startEngines()
  // ...etc
}

Here we're ensuring that we have a fuelCell using optional unwrapping, then using pattern matching to make sure that our (now unwrapped optional) fuel cell has enough fuel in it for us to launch. Right away we can start to see how much clarity this adds.

If either part of our condition fails, we use the else block to run some code then return from the function.

Also as a bonus, the variables we unwrapped in the guard statement are now available, unwrapped, and in-scope for the rest of our function (anything below the guard statement). Neat!

This allows the rest of our function to focus on the actual work being done, rather than checking for validity throughout. We can stack these up too, it's quite common to see multiple guard statements at the top of a functions in Swift.

It's important to note that we aren't required to return at the end of a guard's else block. Imagine using guard in loops to continue, or in a function that throws to throw an error. Guard helps keep our code clean and readable. Happy guarding!