Why the "guard" statement is important in development with Swift
Today, I will tell you what the guard
is, how it works, and why it is important in the Swift development.
TL;DR
The guard
statement is a statement for conditional processing like the if
statement. However, it is recommended to use it not for just conditional processing but for handling optional variables. It enhances readability and safety of your programs by ensuring an optional variable has a value. In that sense, the guard
statement is one way to handle optional bindings rather than mere conditional processing.
The definition
The guard
statement is a statement for conditional processing like the if
statement. The differences from the if
statement are:
The code inside the
else
block is executed when the condition is false.It requires an early exit of from the current scope (by
return
,break
,continue
andthrow
).It can only be used in functions, methods, and computed properties.
A new variable in an expression after the
guard
keyword can be used after theguard
block it the variable is notnil
.
Here is an example:
func exampleFunc(_ a: Int) {
guard a > 0 else {
// code to be exectued when the condition is false
print("The value is negative")
// exit the current scope
return
}
print(a)
}
exampleFunc(12)
// output: 12
As the example shows, the syntax must be like:
guard <boolean> else {
// code to exit the current scope
}
It is useful when checking if arguments are valid at the first.
The guard let
and guard var
statement
In many cases, the guard
keyword is used as guard let
or guard var
. Let's see an example first:
func printMessage(_ message: String?) {
guard let thisMessage = message else {
print("It's nil")
return
}
print(thisMessage)
}
printMessage("Hello, World!")
// output: Hello, World!
You can instantiate a new variable with assigning a value using the guard statement
, which is called conditional binding. Like the example above, it checks if a variable is nil
or not, and executes the code and exits the current scope when the variable is nil
.
Note
Only boolean value can be used after the guard
keyword. However, the expression let thisMessage = message
does not look like a boolean, right? No, it actually is not. In this case, the expression is a conditional binding, which attempts to assign the value of the optional variable. If the assignment succeeds (the optional contains a value), the new variable, which is thisMessage
in this case, is available for use within the rest of the scope. And if the assignment fails (the value is nil
), the code within the else
block is executed and exits the current scope.
Why use guard
Actually, what the guard
statement does can be achieved with the if
statement; there are many languages that do not have the guard
statement or similar syntaxes. However, guard
has a significant feature that if
cannot; guard
can easily and readably check if an optional variable is nil
or not, and the unwrapped variable can be used after guard
statement. Furthermore, it ensures exiting the current scope if the optional variable is nil
. It is safe for handling optional variables. That's why the guard
statement is often used with optional bindings.
In conclusion, guard
is very useful for safely, easily and readably handling variables that can be nil
, which supports a main concept of Swift.
Note
Optional binding is a feature in Swift that allows you to safely unwrap an optional variable and assign its value to a new variable within a limited scope.
The
if
statement also can be used for optional binding. The key differences are that theguard
statement safely ensures early exit (if an optional variable isnil
) and unwrapped variables can be used after theguard
block.