Swift 2.0关键字guard

原创Blog,转载请注明出处
http://blog.csdn.net/hello_hwc?viewmode=list

前言:当一项新的技术出来的时候,第一参考自然是文档。文档链接

guard 语句

guard语句的作用是:当某些条件不满足的情况下,跳出作用域

举个例子:
写个函数,保证输入小于10
在playground输入如下

func testFunc(input:Int){
    guard input < 10 else{
        print("Input must < 10")
        return
    }
    print("Input is \(input)")
}
testFunc(1)
testFunc(11)

可以看到输出

Input is 1
Input must  < 10

上述方法和使用if一样

func testFunc(input:Int){
    if input >= 10{
        print("Input must < 10")
        return
    }
    print("Input is \(input)")
}

但是使用guard有一个好处

如果不使用return,break,continue,throw跳出当前作用域,编译器会报错

所以,对那些对条件要求十分严格的地方,guard是不二之选。

另外,guard也可以使用可选绑定(Optional Binding)也就是 guard let的格式
例如

func testMathFunc(input:Int?){
    guard let _ = input else{
        print("Input cannot be nil")
        return
    }
}

testMathFunc(nil)

如何使用break等跳出关键字?

func testMathFunc(input:[Float]){
    for  tmp in input{
        guard tmp != 3 else{//除数不为0
            print("Can not process 3")
            continue
        }
        print(1.0/(tmp - 3.0))
    }
}
testMathFunc([1.0,2.0,3.0])

输出

-0.5 -1.0 Can not process 3

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...