Skip to content
DeveloperMemos

How to Use guard in Swift

Swift, Error Handling1 min read

In Swift, the guard statement is a powerful tool that can improve the readability and maintainability of your code. Unlike the if statement, which checks a condition and executes code when it's true, the guard statement checks a condition and exits the current scope when it's false.

The Basic Syntax of guard

The basic syntax of guard in Swift is as follows:

1guard condition else {
2 // Code to run if condition is false, such as returning from the function or throwing an error.
3}

Here's an example:

1func divide(_ num1: Int, by num2: Int) -> Int? {
2 guard num2 != 0 else {
3 print("num2 cannot be 0")
4 return nil
5 }
6 return num1 / num2
7}
8
9let result = divide(10, by: 5)
10print(result) // Output: Optional(2)
11
12let invalidResult = divide(10, by: 0)
13print(invalidResult) // Output: nil

In this example, the divide function uses guard to check if num2 is not equal to zero. If it is, the function prints an error message and returns nil. Otherwise, it continues with the division and returns the result.

Using guard with Optionals

One of the most common use cases for guard is with optionals. You can use guard to unwrap an optional and perform a check at the same time. Here's an example:

1func printName(_ name: String?) {
2 guard let name = name else {
3 print("Name is nil")
4 return
5 }
6 print("Hello, \(name)")
7}
8
9printName("John") // Output: Hello, John
10printName(nil) // Output: Name is nil

In this example, the printName function uses guard to unwrap the name optional and check if it's nil. If it is, the function prints an error message and returns. Otherwise, it continues with printing the name.

Using guard with Functions

Another common use case for guard is with functions. You can use guard to check the input parameters of a function and exit early if they're invalid. Here's an example:

1func login(username: String?, password: String?) -> Bool {
2 guard let username = username, let password = password else {
3 print("Please provide both username and password")
4 return false
5 }
6
7 // Validate username and password
8 if isValid(username: username, password: password) {
9 print("Login successful!")
10 return true
11 } else {
12 print("Invalid username or password")
13 return false
14 }
15}
16
17func isValid(username: String, password: String) -> Bool {
18 // Some validation logic here...
19 return true
20}
21
22let success = login(username: "john", password: "password")
23print(success) // Output: Login successful!
24
25let failure = login(username: nil, password: "password")
26print(failure) // Output: Please provide both username and password

In this example, the login function uses guard to check if both username and password are provided. If not, it prints an error message and returns false. Otherwise, it continues with validating the credentials and returns the result.

Summary

In conclusion, the guard statement in Swift is a powerful tool for better error handling and code readability. By using guard, you can exit early when conditions are not met, reducing the complexity and nesting of your code. It's especially useful with optionals and functions, where input validation is important.