Swift Guard语句 提前退出

2017-08-25  本文已影响42人  json_jie

像if语句一样,guard的执行取决于一个表达式的布尔值。我们可以使用guard语句来要求条件必须为真时,以执行guard语句后的代码。不同于if语句,一个guard语句总是有一个else从句,如果条件不为真则执行else从句中的代码。

func greet(person:[String:String]){
    guard  let name = person["name"] else {
        return
    }
    print("Hello \(name)")
    
    guard let location = person["location"] else {
        print("I hope the weather is  nice  near you")
        return
    }
    print("I hope the weather is nice in \(location)")
}
greet(person: ["name":"John"])
print("----------------------------------------------------------------------")
greet(person: ["name":"Jane","location":"Cupertion"])

Log

Hello John
I hope the weather is nice near you


Hello Jane
I hope the weather is nice in Cupertion

  1. 如果guard语句的条件被满足,则继续执行guard语句大括号后的代码。将变量或者常量的可选绑定作为guard语句的条件,都可以保护guard语句后面的代码。

  2. 如果条件不被满足,在else分支上的代码就会被执行。这个分支必须转移控制以退出guard语句出现的代码段。它可以用控制转移语句如return,break,continue或者throw做这件事,或者调用一个不返回的方法或函数,例如fatalError()。

  3. 相比于可以实现同样功能的if语句,按需使用guard语句会提升我们代码的可读性。它可以使你的代码连贯的被执行而不需要将它包在else块中,它可以使你在紧邻条件判断的地方,处理违规的情况

上一篇 下一篇

猜你喜欢

热点阅读