我们知道我们可以使用 if let
语句作为简写来检查可选的 nil 然后展开。
但是,我想使用逻辑 AND 运算符 &&
将它与另一个表达式结合起来。
因此,例如,在这里我执行可选的链接以展开并可选地将我的 rootViewController 向下转换为 tabBarController。但我不想使用嵌套的 if 语句,而是想将它们组合起来。
if let tabBarController = window!.rootViewController as? UITabBarController {
if tabBarController.viewControllers.count > 0 {
println("do stuff")
}
}
联合捐赠:
if let tabBarController = window!.rootViewController as? UITabBarController &&
tabBarController.viewControllers.count > 0 {
println("do stuff")
}
}
上面给出了编译错误Use of unresolved identifier 'tabBarController'
简化:
if let tabBarController = window!.rootViewController as? UITabBarController && true {
println("do stuff")
}
这会产生编译错误条件绑定(bind)中的绑定(bind)值必须是可选类型。尝试了各种语法变体后,每种变体都会给出不同的编译器错误。我还没有找到顺序和括号的最佳组合。
那么,问题是,这是否可能?如果可能,正确的语法是什么?
请注意,我想使用 if
语句而不是 switch
语句或三元 来执行此操作?
运算符。
最佳答案
从 Swift 1.2 开始,现在可以了。 Swift 1.2 and Xcode 6.3 beta release notes状态:
More powerful optional unwrapping with if let — The if let construct can now unwrap multiple optionals at once, as well as include intervening boolean conditions. This lets you express conditional control flow without unnecessary nesting.
使用上面的语句,语法将是:
if let tabBarController = window!.rootViewController as? UITabBarController where tabBarController.viewControllers.count > 0 {
println("do stuff")
}
这使用了 where
子句。
另一个例子,这次将 AnyObject
转换为 Int
,解包可选,并检查解包的可选是否满足条件:
if let w = width as? Int where w < 500
{
println("success!")
}
对于现在使用 Swift 3 的用户,“where”已被逗号取代。因此,等效的是:
if let w = width as? Int, w < 500
{
println("success!")
}
关于swift - 使用带有逻辑 AND 运算符 && 的 Swift if let,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25202770/