//swift guard语句
/*
与if语句相同的是,guard也是基于一个表达式的布尔值去判断一段代码是否该被执行。与if语句不同的是,guard只有在条件不满足的时候才会执行这段代码。你可以把guard近似的看做是Assert,但是你可以优雅的退出而非崩溃。
是对你所期望的条件做检查,而非不符合你期望的。又是和assert很相似。如果条件不符合,guard的else语句就运行,从而退出这个函数。
如果通过了条件判断,可选类型的变量在guard语句被调用的范围内会被自动的拆包 -这个例子中该范围是fooGuard函数内部。这是一个很重要,却有点奇怪的特性,但让guard语句十分实用。
对你所不期望的情况早做检查,使得你写的函数更易读,更易维护。
*/
func fooNonOptionalGood(x:Int) ->Bool{
guard x > 0else {
//执行不满足条件时的操作
print("x<=0,不满足条件退出")
return false
}
print("x > 0,x的值是:\(x)")
return true
}
fooNonOptionalGood(5)
fooNonOptionalGood(-2)
//guard demo2
guard优点
1、代码清爽直观。
2、不必再if套if,会混淆你的逻辑。
3、if let name = person["name"]{}其中name的作用域仅局限于紧随的大括号中,而guard let name = person["name"]范围更广!
//使用if-let解包
func greet_if(person:[String:String]) {
if let name = person["name"] {
print("输入name:Hello\(name)")//名字存在
if let location = person["location"] {
print("输入location:I hope the weather is nice in\(location)")
} else {
print("location未输入:I hope the weather is nice near you")
return;
}
} else {
print("没输入名字直接退出")
return;
}
}
greet_if(["name":"json","location":"NewYork"])
greet_if(["name":"json"])
greet_if(["location":"NewYork"])
//使用guard改写
func greet_guard (person:[String:String]) {
guard let name = person["name"]else {
print("没输入名字直接退出")
return;
}
print("输入name:Hello\(name)")//名字存在
guard let location = person["location"]else{
print("location未输入:I hope the weather is nice near you")
return;
}
print("输入location:I hope the weather is nice in\(location)")
}
greet_guard(["name":"json","location":"NewYork"])
greet_guard(["name":"json"])
greet_guard(["location":"NewYork"])
/*
执行结果:
输入name:Hello json
输入location:I hope the weather is nice in NewYork
输入name:Hello json
location 未输入:I hope the weather is nice near you
没输入名字直接退出
*/