Swift 2.0关键字guard
发布时间:2020-12-14 01:47:04 所属栏目:百科 来源:网络整理
导读:原创Blog,转载请注明出处 http://blog.csdn.net/hello_hwc?viewmode=list 前言:当一项新的技术出来的时候,第一参考自然是文档。文档链接 guard 语句 guard语句的作用是:当某些条件不满足的情况下,跳出作用域 举个例子: 写个函数,保证输入小于10 在pla
原创Blog,转载请注明出处 前言:当一项新的技术出来的时候,第一参考自然是文档。文档链接 guard 语句
举个例子: 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有一个好处 如果不使用
另外,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
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |