- Learn Swift by Building Applications
- Emil Atanasov
- 160字
- 2021-06-25 22:13:48
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.
推薦閱讀
- SPSS數(shù)據(jù)挖掘與案例分析應(yīng)用實(shí)踐
- Clojure Programming Cookbook
- Java程序設(shè)計(慕課版)
- Designing Hyper-V Solutions
- 程序員考試案例梳理、真題透解與強(qiáng)化訓(xùn)練
- 零基礎(chǔ)學(xué)Java(第4版)
- Effective Python Penetration Testing
- 利用Python進(jìn)行數(shù)據(jù)分析(原書第3版)
- 深入理解Elasticsearch(原書第3版)
- Android開發(fā):從0到1 (清華開發(fā)者書庫)
- Node.js開發(fā)指南
- Learning Ionic
- 零基礎(chǔ)學(xué)Java第2版
- Python機(jī)器學(xué)習(xí)開發(fā)實(shí)戰(zhàn)
- 百萬在線:大型游戲服務(wù)端開發(fā)