April 2017
Intermediate to advanced
316 pages
9h 33m
English
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 ...
Read now
Unlock full access