Swift Functional Programming(Second Edition)
上QQ阅读APP看书,第一时间看更新

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.