Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the Swift if let with logical AND operator &&

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 using the logical AND operator &&.

So, for example, here I do optional chaining to unwrap and optionally downcast my rootViewController to tabBarController. But rather than have nested if statements, I'd like to combine them.

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

Combined giving:

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

The above gives the compilation error Use of unresolved identifier 'tabBarController'

Simplifying:

if let tabBarController = window!.rootViewController as? UITabBarController && true {    println("do stuff") } 

This gives a compilation error Bound value in a conditional binding must be of Optional type. Having attempted various syntactic variations, each gives a different compiler error. I've yet to find the winning combination of order and parentheses.

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

Note that I want to do this with an if statement not a switch statement or a ternary ? operator.

like image 253
Max MacLeod Avatar asked Aug 08 '14 11:08

Max MacLeod


2 Answers

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!") } 
like image 86
Max MacLeod Avatar answered Sep 21 '22 10:09

Max MacLeod


In Swift 3 Max MacLeod's example would look like this:

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

The where was replaced by ,

like image 43
ph1lb4 Avatar answered Sep 18 '22 10:09

ph1lb4