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

A 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)!") } 

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. As can be seen from the example, the scope of the guarded variable is not only the guard code block, so we were able to use name after the guard code block in our print statement.

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