Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Using Guard Statement with Optionals
Written by Team Kodeco

The guard statement in Swift is used to safely unwrap optionals. It allows you to check for a condition and if that condition isn’t met, it exits the current scope, preventing the optional from being unwrapped.

Here is an example of using a guard statement to safely unwrap an optional:

func processData(data: Data?) {
  guard let data else {
    print("No data found")
    return
  }
  // process the data
}

In this example, the guard statement checks if the data variable is not nil. If data is nil, the guard statement triggers the else block and the function exits, preventing the code inside the function from executing. If data is not nil, the optional is unwrapped and the code inside the function continues to execute.

An analogy for the guard statement is a bouncer at a club. Before allowing someone to enter the club, the bouncer checks for a valid ID. If the ID is not valid, the bouncer doesn’t allow the person to enter the club. Similarly, the guard statement checks for a condition and if it’s not met, returns.

Using Multiple Guard Statements

You can also use multiple guard statements for multiple optionals in the same scope. This can make your code more readable.

func processData(data: Data?, metadata: Metadata?) {
  guard let data else {
    print("No data found")
    return
  }
  guard let metadata else {
    print("No metadata found")
    return
  }
  // process the data and metadata
}

This way, if the first optional isn’t present, the second guard statement won’t be executed.

© 2024 Kodeco Inc.