All Articles

Swift guard statement

A guard statement is a way of exiting a program if a condition is not met. The basic structure looks like the following:

guard (condition we want true) else {
(statements) //return, break, etc...
}

Also called the Bouncer Pattern, it takes care of the problem before it even enters the club. Why is this helpful? It makes your code more clear and concise. The code tells the compiler that if the condition is not met, then break out of the function.

Basically, we want to check for the unwanted case early on.

To use a guard statement, you must always have an else included, as well as one of the following statements:

  • return
  • break
  • throw
  • continue

Let’s look at some examples below.

Example 1:

func ageGuard (age: Int) {
    guard age >= 21 else {
        print("You are under 21, so you may not order alcohol.")
        return
    }
    print("You're 21 or over! You may order alcohol.")
}

Example 2 (with an optional):

func ageGuardOptional (age: Int?) {
    guard let age = age, age >= 21 else {
        print("You are under 21, so you may not order alcohol.")
        return
    }

    print("Since you are 21 or older, you may drink alcohol.")
}
 
ageGuardOptional(age: 23) //will print "Since you are 21 or older, you may drink alcohol."
ageGuardOptional(age: 20) //will print "You are under 21, so you may not order alcohol."