
上QQ阅读APP看书,第一时间看更新
What is the guard statement?
The guard statement has similar behavior to an if statement. This statement checks the condition, and if it's not met, then the else clause is triggered. In the else clause, the developer should finish the current function or program, because the prerequisites won't be met. Take a look at the following code:
func generateGreeting(_ greeting: String?) -> String {
guard let greeting = greeting else {
//there is no greeting, we return something and finish
return "No greeting :("
}
//there is a greeting and we generate a greeting message
return greeting + " Swift 4!"
}
print(generateGreeting(nil))
print(generateGreeting("Hey"))
This is a tiny example, showing us code that illustrates the regular usage of the guard statement. We can combine it with the where clause, or we can make the check really complex. Usually, it's used when the code depends on several if...let checks. The guard statement keeps the code concise.