Swift guard Statement

In Swift, we use the guard statement to transfer program control out of scope when certain conditions are not met.

The guard statement is similar to the if statement with one major difference. The if statement runs when a certain condition is met. However, the guard statement runs when a certain condition is not met.


Syntax of guard Statement

The syntax of the guard statement is:

guard expression else {
  // statements
  // control statement: return, break, continue or throw.
}

Here, expression returns either true or false. If the expression evaluates to

  • true - statements inside the code block of guard are not executed
  • false - statements inside the code block of guard are executed

Note: We must use return, break, continue or throw to exit from the guard scope.


Working of Swift guard Statement

How guard statement works in Swift
Working of guard statement in Swift

Example: Swift Guard Statement

var i = 2

while (i <= 10) {
    
  // guard condition to check the even number 
  guard i % 2 == 0 else {
   
     i = i + 1
    continue
  }

  print(i)
  i = i + 1
} 

Output

2
4
6
8
10

In the above example, we have used the guard statement to check if the number is even or odd. Notice the line,

guard i % 2 == 0 else {...}

Here, if i is

  • odd - , i % 2== 0 evaluates to false. And, the code inside the guard is executed.
  • even - , i % 2 == 0 evaluates to true. And, the code inside the guard is skipped.

Hence, we only get the even numbers as our output.

We have used the continue statement inside guard to transfer the control to the next iteration of the loop.

Note: The use of control statements like continue, break, etc. is compulsory. Otherwise, we will get an error: 'guard' body must not fall through, consider using a 'continue' or 'return' to exit the scope.


guard Statement Inside a Function

The guard statement is generally used with functions. A function is a block of code that performs a specific task. To learn more, visit Swift Function.

Let's see how we can use a guard statement with functions.

// create a function
func checkOddEven() {
  var number = 23

  // use of guard statement
  guard number % 2 == 0 else {
    
    print("Odd Number")
    return
  }

  print("Even Number")
}

// function call
checkOddEven()

Output

Odd Number

In the above example, we have created a function named checkOddEven(). Notice the use of guard statement inside the function.

guard number % 2 == 0 else {
    
  print("Odd Number")
  return
}

Here, the guard statement checks if the number is even or odd. Since the number is odd, the condition number % 2 == 0 returns false.

Hence, the code inside the guard statement is executed.

Now, let's change the value of number to an even number, say 24.

// create a function
func checkOddEven() {
  var number = 24

  // use of guard statement
  guard number % 2 == 0 else {
    
    print("Odd Number")
    return
  }

  print("Even Number")
}

// function call
checkOddEven()

Output

Even Number

Here, since the number is even, the condition number % 2 == 0 evaluates to true.

So, the code inside the guard statement is skipped and the other code inside of the function is executed. Hence, we get Even Number as an output


guard with multiple conditions

guard statements can also chain multiple conditions separated by comma (,) as:

func checkJobEligibility() {
    
  var age = 33

  guard age >= 18, age <= 40 else {
    print("Not Eligible for Job")
    return
  }

  print("You are eligible for this job")

}

checkJobEligibility()

Output

You are eligible for this job

In the above example, the guard statement contains two conditions separated by a comma.

Here, there will be the Logical AND relation between two conditions. That is, the guard condition is true only if both conditions are true.


guard-let Statement

While working with Swift Optionals, the guard statement is used as the guard-let statement. For example,

func checkAge() {
	
  var age: Int? = 22

  guard let myAge = age else {
    print("Age is undefined")
    return
  }

  print("My age is \(myAge)")
}

checkAge()

Output

My age is 22

In the above example, we have created an optional variable named age. Here, we are using the guard-let statement to check whether age contains a value or not.

Since age contains some value, the code inside the guard-let block is not executed. This works similar to the condition of guard being true.


guard Vs if Statement

The guard statement is introduced as an alternative to the if statement. For example,

Suppose we want to check if a person is eligible to vote, we can use the if statement as:

func voteEligibility() {
    
  var age = 42

  if age >= 18 {
  print("Eligible to vote")
  }
  else {
  print("Not eligible to vote")
  }

}

voteEligibility()

Output

Eligible to vote

This same program can be written using the guard statement as:

func voteEligibility() {
    
  var age = 42

  guard age >= 18 else {
  print("Not Eligible to vote")
  return
  }

  print("Eligible to vote")
}

voteEligibility()

Output

Eligible to vote

As you can see, with the guard statement, we can exit from the function as soon as the condition evaluates to false.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges