A Quick Rundown of How to Use “Guard” and “Guard let”

Michelle Lau
3 min readNov 23, 2020

--

So you’re learning Swift and you’ve wrapped your head around unwrapping optionals (ba dum tss). One of the next concepts you’ll most likely encounter is the guard statement.

Let’s see a real-world example of how to use it. This is a login screen for an app that uses Firebase Authentication. We have an email and password text field.

The code in its entirety can be found here.

You might be inclined to use the nil coalescing operator as a quick way to unwrap the optional. Or, you might use optional binding to unwrap it. But, as you may have seen in other articles, you will end up with a headache of nested “if-let” statements.

Instead, you can use “guard let” to unwrap it. If it can’t be unwrapped, the function will exit, which is also known as an early exit.

Unwrapping with “guard let” looks a lot cleaner.

The benefit of using “guard let” instead of optional binding is that the unwrapped value is available to use throughout the rest of the block.

See the example of the optional binding below, where the unwrapped value is only available within the “if-let” block. Outside of it, Xcode has “no idea” what that value is.

Now let’s take a look at error handling with “guard.” The condition that you’re looking for is the happy path (error == nil).

As opposed to this “if/else” statement in which the happy path just so happens to come first. But anyway, they essentially do the same thing.

This article highlighted the benefits of using Guard, but the following article by Alexey Kuznetsov goes into detail of when it’s not a good idea to use it.

Happy Swift Coding!

Comments and feedback are welcome~

--

--