📅  最后修改于: 2021-01-11 07:35:41             🧑  作者: Mango
Swift Guard语句代替了Swift if语句。与if语句相比,Guard语句具有更多的优点,可以控制程序流并编写简单干净的代码。
guard expression else {
//statements
//must contain a control statement:return, break, continue or throw.
}
注意:guard语句必须在代码末尾包含控制语句return,break,continue或throw。
guard true else {
print("Condition is not satisfied.")
}
print("Condition is satisfied.")
输出:
Condition is satisfied.
函数内部的Guard语句
在Swift中,我们也可以在函数使用保护声明。
func Function1() {
guard false else {
print("Condition is not satisfied.")
return
}
print("Condition is satisfied.")
}
Function1()
print("Hello after function call")
输出:
Condition is not satisfied.
Hello after function call