Using Guard to early exit in Swift

Swift 3

You can use Guard to early exit a loop or function to prevent the rest of the code executing when it doesn’t have what it needs to run. This kind of safety is what makes apps stable when things go unexpectedly wrong.

Consider you have a function that builds a filename from data in your app.

We can not afford empty strings, which may cause crashes elsewhere in the app. For the sake of safety, it would be a good idea to make the function return an optional, and check for empty strings.

This works, but if the function was complex, and lots of code generated the filename, then we need it to exit early if the function did not have what we needed to generate a safe filename.

Using guard in a function

Let’s use guard to exit early.

The guard statement will return nil if the test given to it returns false. Below this, we know that name and suffix are not empty, so we can use them with confidence and return the result. This allows the code to be shorter, and more readable after the guard statement.

You can do the same thing with a loop. Lets look at an example of a guard statement speeding up a loop by exiting early using continue.

Using guard in a loop

In this example, we have an array of optional Strings, but one of them is nil.

With Guard, you can use return, break or continue to exit out of code early.


Guard can save CPU cycles in a loop or lots of testing during a function, and has the added benefit of making the code more readable, and much safer.

Leave a Reply

Your email address will not be published. Required fields are marked *