Swift guard statement — need to know with examples

In Swift the guard statement is a control flow statement that is used to check for certain conditions, and if those conditions are not met, it will exit the current scope early, returning from the current function, method, or closure.

The primary use of guard is for an early exit, as opposed to using nested if statements to check for error conditions. It allows the developer to make the code more readable by reducing the level of nesting and making the error handling code more clear.

How to use the guard statement

A guard statement starts with the guard keyword, followed by a boolean expression that must be true for the code to continue. If the expression evaluates to false, the code in the else block will be executed. The else block can contain any code that will exit the current scope, such as a return statement, throw statement, or a call to fatalError().

Here is an example of a guard statement:

func process(data: String?) {
    guard let data = data else {
        print("Data is nil")
        return
    }
    print("Processing data: \(data)")
    // rest of the function code
}

In this example, the guard statement checks if the data parameter is not nil. If the parameter is nil, the code in the else block is executed, which prints an error message and exits the function early. If the data parameter is not nil, the code continues to execute normally.

Swift guard statement with multiple conditions

Often you will find yourself checking for multiple conditions in a function and luckily you can easily add multiple conditions to your guard statement. All you have to do is add a comma between your conditions.

func process(data: String?, processData: Bool?) {
    guard let data = data, processData else {
        print("Data is nil")
        return
    }
    print("Processing data: \(data)")
    // rest of the function code
}

In the code example above the guard statement is checking if the data is nil and if processData true, and the function will only continue if both the statements is true.

When to use guard statement

The guard statement is primarily used for an early exit from a function or method when certain conditions are not met. It’s typically used to validate the input parameters of a function or method and to ensure that the code can safely proceed before executing the main logic.

Here are some guidelines on when to use guard statements in Swift:

  1. Validating input: guard statements are commonly used to validate the input parameters of a function or method. This can include checking that the parameters are not nil, that they have valid values, or that they conform to certain requirements. By using guard to validate input, the code can exit early if the input is invalid, reducing the risk of unexpected errors later on.
  2. Simplifying nested if statements: guard can be used to simplify nested if statements and reduce the level of nesting in the code. This can make the code more readable and easier to understand, as it separates the main logic from the error handling.
  3. Improving error handling: By using guard statements to handle errors and invalid input, the code can provide more specific and descriptive error messages, making it easier to debug and maintain the code. It can also help to catch errors earlier before they cause more serious problems or crashes.
  4. Ensuring safety: guard statements can also be used to ensure safety and prevent unexpected behavior in the code. The code can avoid unexpected results or undefined behavior by validating input and checking for specific conditions early on.

Overall, guard statements can be used in many different situations in Swift, but they are most commonly used for input validation, simplifying nested if statements, improving error handling, and ensuring safety.

Scroll to Top