Swift guard statement
A guard statement is used to transfer program control out of scope if one or more conditions are not met. Unlike if guard statements only run when certain conditions are not met.
guard expression else {
// statements
// must contain a control statement:return, break, continue or throw.
}- Here,
expressionis a boolean expression that returns eithertrueorfalse. - If the
expressionis evaluated tofalse, statements inside the code block ofguardis executed. - If the
expressionis evaluated totrue, statements inside the code block ofguardare skipped from execution. - The end of the
guardstatement(statements inside the guard) must contain a control statementreturn,break,continueorthrowto exit from the scope.
func taskFunc() {
guard false else {
print("Statements inside guard are being executed")
return
}
print("Statements outside guard are being executed")
}
taskFunc()In the above Swift code, the guard condition evaluates to false, therefore the statements inside the guard executes. The first statement print("Statements inside guard are being executed") outputs "Statements inside guard are being executed" in the console.
The statement return terminates execution of a function and thus the statement outside and after guard of the taskFunc are not getting executed.
Guard with optionals
We know in Swift Optionals the use of if-let to unwrap an optional. However, we can also use guard statement in place of if-let for unwrapping an optional with one advantage. The main advantage of unwrapping an optional with guard instead of if-let is we can increase scope of the unwrapped variable.
func parseInt(value: String) {
guard let number = Int(value) else {
return nil
}
return number
}In the above Swift code, we can see the unwrapped value number is being used outside of the scope defined by guard statement. Since, number is defined optional and contains Int value, the guard statement unwrapps the value and it returns number or nil based on the input value type-casts result.
An exmaple of using guard in practical Swift development
func parseInt(value: String) -> Int? {
guard let number = Int(value) else {
return nil
}
return number
}
let qty = (parseInt(value: "9") ?? 0)
print("Quantity is = \(qty)")In the above Swift code, we can see the type-casted value number is being used outside of the scope defined by guard statement. Since, value is defined String and contains "9" value, the guard statement type-casts the value and it outputs "Quantity is : 9" in the console.
Conclusion
The guard and guard let statements make our code easier to read, safer, and less error-prone.