O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required