We have seen in previous recipes how we can use if statements to check Boolean expressions and unwrap optional values. It's a common use case to want to do some checks and conditional unwrapping at the beginning of a block of code, and then only execute the subsequent code if everything is as expected. This usually results in wrapping the whole block of code in an if statement:
if <#boolean check and unwrapping#> {
<#a block of code#>
<#that could be quite long#>
}
Swift has a better solution expressly for this purpose; the guard statement.
In this recipe, we will learn how to use the guard statement to return early from a method.