微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐