---
title: "#205: Swift guard Basics ⚔"
url: https://littlebitesofcocoa.com/205-swift-guard-basics
author: Jake Marsh
published: 2016-03-04
topics: ["Swift","Techniques"]
description: "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."
---

# #205: Swift guard Basics ⚔

By Jake Marsh, March 4, 2016. HTML: https://littlebitesofcocoa.com/205-swift-guard-basics

The _guard_ statement was added to **Swift** in its **2.0** release. It can <i>dramatically</i> increase the readability and clarity of the conditional checks in our code.

It supports **Swift's** inline [optional unwrapping](https://littlebitesofcocoa.com/173) as well as [pattern matching](https://littlebitesofcocoa.com/22). Let's try it out!

We can think of the `guard` **statement** like a sort of inverted `if` **statement**. We essentially say: <i>"this thing must be true otherwise we're bailing out!". </i>Here's a fairly full-featured example:

``` swift
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 (<i>now unwrapped optional</i>) 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, <i>and</i> 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 <i>required</i> 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_!
