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.
var foo : Int? = 10; if let bar = foo { if bar == 10 { println("Great success!") }}
– Labellumif let bar = foo && bar == 10
isUse of unresolved identifier "bar"
(on the secondbar
, of course). – LabellumbridgeToObjectiveC
is gone in beta 5 (and was quite possibly never intended for general use). 2. There's afirst
method on Swift's built-inArray
type anyway. – Quinquennium