Using the Swift if let with logical AND operator &&

前端 未结 6 479
名媛妹妹
名媛妹妹 2021-01-30 19:13

We know that we can use an if let statement as a shorthand to check for an optional nil then unwrap.

However, I want to combine that with another expression

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-30 19:59

    As of Swift 1.2, this is now possible. The Swift 1.2 and Xcode 6.3 beta release notes state:

    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.

    With the statement above, the syntax would then be:

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

    This uses the where clause.

    Another example, this time casting AnyObject to Int, unwrapping the optional, and checking that the unwrapped optional meets the condition:

    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!")
    }
    

提交回复
热议问题