Guard
The guard is another method provided in the Swift library to handle Optionals. The guard method differs from the Optionalif-let binding in that the guard statement can be used for early exits. We can use a guard statement to require that a condition must be true in order for the code after the guard statement to be executed.
The following example presents the guard statement usage:
func greet(person: [String: String]) {
guard let name = person["name"] else {
return
}
print("Hello Ms \(name)!")
}
greet(person: ["name": "Neco"]) // prints "Hello Ms Neco!" In this example, the greet function requires a value for a person's name; therefore, it checks whether it is present with the guard statement. Otherwise, it will return and not continue to execute.
Using guard statements, we can check for failure scenarios first and return if it fails. Unlike if-let statements, guard does not provide a new scope, so in the preceding example, we were able to use name in our print...