Textlogo_codingem_white

Programming tips for everyone

The Guard Keyword in Swift

Guard in Swift checks if a value exists. If it doesn’t then it exits the scope. For instance, the guard can be used to jump out from a function if the input is wrong.

Why Guard

Once upon a time in Swift, there was a pyramid of doom. This antipattern was a typical sight in Swift: When a method runs, you want to be sure all the necessary data is available before doing work.

This task could be solved in one of two possible ways:

  • Using what is known as a pyramid of doom
  • Using early returns


The former looks something like this:

if username != "" {
     if email != "" {
         if age != "" {
             // do something...
         }
     }
 }

This is called the pyramid of doom due to the shape of the code. It reminds a pyramid.

The latter approach looks something like this:

if username == "" { return }
if email == "" { return }
if age == "" { return }
 // do something…


This is known as an early return due to the fact that you return from a method as early as possible. The idea is to “stay in the method as long as safe”.

Even though both of these approaches work, neither of them looks pleasing nor are they problem-free:

  • The pyramid of doom only grows and grows when there are more things to check
  • The early returns are somewhat confusing as the reason why you’re returning is hazy. Also, with these you are actually checking the opposite to what you actually care about: To check for a valid username you check if username is empty…
  • Also, the way early return handles optionals is problematic. If you use an if/let construct inside of your early return, the unwrapped optional leaves the scope immediately, so you can’t use it. When this happens, you either re-unwrap it, or you force unwrap now that you know it exists. This is bad practice.

Guard in Swift to Resolve the Issue

There is a keyword guard you can use to improve the early returns:

  • Using guard the intent becomes clear. You can tell the guard directly what you want instead of checking against the opposite.
  • The guard is useful when trapping invalid values passed into the function as the syntax makes you instantly understand what it is doing.
  • You can unwrap optionals with the guard. When doing this, the unwrapped values stay around so you can use them. In other words, you can validate optionals by unwrapping them and directly using them.
  • Using guard also saves some lines of code.

Here are some examples of using guard:

guard username.count > 0 else {
    throw InputError.Empty
}
guard age > 18 else {
     return false
}
// Unwrapped optionals remain in the scope
func show(username: String?) {
    guard let username = username else {
        print("Name is empty")
        return
    }
    print(username)
 }



Thanks for reading. I hope you learned something new today.

Happy coding!

You May Find Insightful

Swift – Upgrade Your Skills with These 5 Tips

iOS Development Tips in 2021

Share on facebook
Share on twitter
Share on linkedin

Related Articles

Artturi Jalli

Technical Writer

Entrepreneur, Software Engineer, Mobile App Dev, MSc Physics Student, And Tech Enthusiast from Finland

artturi@codingem.com

My Personal Favorites
Sponsor

Buy an Online Course

Lorem ipsum dolor sit amet consectetur adipiscing elit dolor
Explore Categories

Web Development