我们知道,我们可以使用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")
}

这将导致编译错误Bound value in a conditional binding must be of Optional type.try 了各种语法变体后,每种变体都会给出不同的编译器错误.我还没有找到顺序和括号的最佳组合.

So, the question is, is it possible and if so what is correct syntax?

Note that I want to do this with an 100 statement 103 a 101 statement or a ternary 102 operator.

推荐答案

从Swift 1.2开始,这是is now possible.Swift 1.2 and Xcode 6.3 beta release notes个州:

More powerful optional unwrapping with if let-if let构造

使用上面的语句,语法将是:

if let tabBarController = window!.rootViewController as? UITabBarController where tabBarController.viewControllers.count > 0 {
        println("do stuff")
}

这使用了where条款.

另一个例子是,这一次从AnyObjectInt,展开可选项,并判断展开的可选项是否满足条件:

if let w = width as? Int where w < 500
{
    println("success!")
}

For those now using Swift 3, "where" has been replaced by a comma. The equivalent would therefore be:

if let w = width as? Int, w < 500
{
    println("success!")
}

Swift相关问答推荐

Swift C外部实现的Task / Future类类型

在数组中查找最大y值的x值

Swift计时器未触发

使用异步收集发布者值

可以使 Swift init 仅可用于 Objective C 吗?

为什么我在我的 Swift iOS 应用程序项目中收到 Xcode 中的错误消息无法识别的 Select 器发送到类?

使用 swift 的 Firebase 身份验证

我如何遵守与演员的协议?

Swift 根据总值将数组拆分为块

Swift 全局函数列表

将 struct 作为泛型类型传递并访问该泛型类型属性

SwiftUI:异步网络请求后@State 值不更新

如何有条件地依赖桌面与 iOS 的系统库?

来自数据的 SwiftUI 图像

ZStack 中的 ProgressView 与 View 的行为不同

引用类型(类)不需要但 struct 需要的可识别 id

Swift 2 或 3 中的 Google Analytics 问题

Xcode 7.3 Swift 的语法高亮和代码完成问题

如何在 GCD 中停止 DispatchWorkItem?

SwiftUI - 呈现工作表后导航栏按钮不可点击