我们知道我们可以使用if let语句作为速记来检查可选的nil然后解包.
但是,我想使用逻辑AND运算符将其与另一个表达式相结合&&.
因此,例如,在这里,我执行可选链接以解包并可选地将我的rootViewController向下转换为tabBarController.但是我没有嵌套if语句,而是将它们组合起来.
if let tabBarController = window!.rootViewController as? UITabBarController {
if tabBarController.viewControllers.count > 0 {
println("do stuff")
}
}
Run Code Online (Sandbox Code Playgroud)
综合给予:
if let tabBarController = window!.rootViewController as? UITabBarController &&
tabBarController.viewControllers.count > 0 {
println("do stuff")
}
}
Run Code Online (Sandbox Code Playgroud)
上面给出了编译错误使用未解析的标识符'tabBarController'
简化:
if let tabBarController = window!.rootViewController as? UITabBarController && true {
println("do stuff")
}
Run Code Online (Sandbox Code Playgroud)
这给出了编译错误条件绑定中的Bound值必须是Optional类型.尝试了各种语法变体后,每个都会产生不同的编译错误.我还没有找到订单和括号的获胜组合.
所以,问题是,是否可能,如果是这样,什么是正确的语法?
请注意,我想与做这个if说法不是一个switch语句或三元?运营商.
Max*_*eod 131
从Swift 1.2开始,现在可以实现.在雨燕1.2与6.3的Xcode beta版笔记状态:
使用 if 更强大的可选展开 - if let结构现在可以立即解包多个选项,以及包含干预布尔条件.这使您可以表达条件控制流而无需不必要的嵌套.
通过上面的语句,语法将是:
if let tabBarController = window!.rootViewController as? UITabBarController where tabBarController.viewControllers.count > 0 {
println("do stuff")
}
Run Code Online (Sandbox Code Playgroud)
这使用了该where条款.
另一个例子,这次转换AnyObject为Int,展开可选项,并检查未包装的可选项是否满足条件:
if let w = width as? Int where w < 500
{
println("success!")
}
Run Code Online (Sandbox Code Playgroud)
对于那些现在使用Swift 3的人,"where"已被逗号替换.因此,等价物将是:
if let w = width as? Int, w < 500
{
println("success!")
}
Run Code Online (Sandbox Code Playgroud)
ph1*_*lb4 55
在Swift 3 Max MacLeod的例子中看起来像这样:
if let tabBarController = window!.rootViewController as? UITabBarController, tabBarController.viewControllers.count > 0 {
println("do stuff")
}
Run Code Online (Sandbox Code Playgroud)
将where被替换,
par*_*par 37
Max的答案是正确的,这是一种方法.请注意,当这样写时:
if let a = someOptional where someBool { }
该someOptional表达式将首先被解决.如果失败,那么someBool表达式将不会被评估(短路评估,正如您所期望的那样).
如果你想以相反的方式写这个,可以这样做:
if someBool, let a = someOptional { }
在这种情况下,someBool首先进行评估,并且仅当评估为true时才评估someOptional表达式.
Swift 4,我会用,
let i = navigationController?.viewControllers.index(of: self)
if let index = i, index > 0, let parent = navigationController?.viewControllers[index-1] {
// access parent
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34014 次 |
| 最近记录: |