What is a guard statement in Swift?


In this tutorial, you will learn about what is a guard statement and how it is implemented in the Swift language. Let's learn.

What is a guard statement?

In Swift, the guard is a statement that transfers control between codes like an if-else statement. The guard statement is the most commonly used statement in Swift. When certain conditions are not met to allow the flow to continue, the guard statement is used to transfer flow control.

A guard statement is similar to an 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

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

In the above syntax, the expression returns either true or false. If the expression evaluates to

  • true − guard does not execute statements inside its code block

  • false − guard executes statements inside its code block

Note − It is mandatory to use return, break, continue or throw to exit the guard scope.

Example

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

Output

2
4
6
8
10

Guard statement to unwrap the optional value

In Swift, you can unwrap a value from an optional variable like the below −

Example

func doSomething() { let name: String? = "Amit Saxena" guard let nameString = name else { print("name is not found") return } print("Name found: \(nameString)") } doSomething()

Output

Name found: Amit Saxena

Guard statement with multiple conditions

Syntax

guard condition1, condition2, conditionN else {
   
   // statements
   return
}

The guard statement can be used to check for multiple conditions. If all conditions are met, further code will be executed, otherwise, the guard's body will be executed and returned.

Example

class Student { var name: String? var age: Int? var address: String? func allDataValid() -> Bool { guard let nameString = name, let age = age, let address = address else { print("some data is not valid.") return false } print("Name: \(nameString), age: \(age), address: \(address)") return true } } let amit = Student() print(amit.allDataValid())

Output

some data is not valid.
false

Guard with an Enum Case

Enumeration cases can also be matched using the guard statement. You can use the guard to check if an enumeration object matches the desired case.

Example

enum ErrorState { case noInternet case serverNotReachable case somethingWrong case none } func perform(state: ErrorState) { guard case state = ErrorState.none else { print("Some error found, cannot execute further code.") return } print("No error found") } perform(state: ErrorState.serverNotReachable)

Output

Some error found, cannot execute further code.

Explanation

In the above example, we have created an enum for ErrorState with different cases. Now in the perform() function, we are checking for an error state using an enum case and returning if any error is found other than none case. You can see how flexible the guard statement can be to check different conditions.

Benefits of using Guard Statement in Swift

The guard statement is very useful in making your code readable and maintainable. There are some reasons why you should use the guard statement −

  • It becomes clear what the code is trying to accomplish. Instead of telling the guard what you don't want, you can tell him directly what you want.

  • The function should be able to detect invalid arguments.

  • Make unwrapped values usable by unwrapping optionals with the guard.

  • Reduce the number of lines of code.

Conclusion

The guard statement in Swift was explained to you. When certain situations arise, the guard statement solves the issue of code readability. With a guard, a piece of code could be written in a clean manner. Further, you can learn about other statements like if-else, switch, etc.

Updated on: 22-Nov-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements