官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 正阳县| 黄平县| 福贡县| 乌海市| 连山| 石首市| 甘谷县| 雅江县| 惠水县| 绥中县| 赤峰市| 陇川县| 阜城县| 临泽县| 和政县| 毕节市| 潞城市| 河津市| 张家港市| 婺源县| 娱乐| 太白县| 延安市| 凤凰县| 吉木乃县| 潍坊市| 泾源县| 扶余县| 宜黄县| 环江| 喀喇| 谢通门县| 开鲁县| 灌云县| 广州市| 平原县| 济阳县| 清远市| 濮阳市| 安庆市| 大宁县|