Using the Swift if let with logical AND operator &&

if let swift
nil coalescing operator swift
swift if let multiple
if let assignment swift
swift if let nil
swift if let data data
let binding swift
switch if let

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'


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.

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

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

Basic Operators, For example, the addition operator ( + ) adds two numbers, as in let i = 1 + 2 , and the logical AND operator ( && ) combines two Boolean values, as in if You can opt in to value overflow behavior by using Swift's overflow operators,  No, you can't OR two if-let statements, or even an if-let statement with a non if-let condition, because that would completely defeat the purpose of the if-let statement. if-let ensures that you can only enter the body of the statement if the optional could be successfully unwrapped into the variable.

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 ,

Optional binding and defer statements in iOS swift, The drawback of if let and if var statements are that any variables or constants that were assigned values using an optional binding are availabe  Logical AND (x && y) Operator. In swift Logical AND operator will check if all defined conditions are true or not. Following is the simple example of using Logical AND operator in swift programming language.

Max's answer is correct and one way of doing this. Notice though that when written this way:

if let a = someOptional where someBool { }

The someOptional expression will be resolved first. If it fails then the someBool expression will not be evaluated (short-circuit evaluation, as you'd expect).

If you want to write this the other way around it can be done like so:

if someBool, let a = someOptional { }

In this case someBool is evaluated first, and only if it evaluates to true is the someOptional expression evaluated.

Conditionals In Swift With If, Else If, Else – LearnAppMaking, You use conditionals to make decisions in Swift with if, else if and else. In this article you learn about logic, expressions, operators, and Swift syntax. Let's take a look at the Swift syntax for conditionals. Here's an example: if  It’s a comparison operator, and you use it to check if two values are equal. Swift has the following comparison operators: Equal to: a == b; Not equal to: a != b; Greater than: a > b; Less than: a < b; Greater than or equal to: a >= b; Less than or equal to: a <= b; You use comparison operators to compare values with each other.

Swift 4, I will use,

let i = navigationController?.viewControllers.index(of: self)
if let index = i, index > 0, let parent = navigationController?.viewControllers[index-1] {
    // access parent

Swift 3 Logical AND OR operators, //set up a bunch of conditional variables to test in our if statement that contains AND plus OR operators. let hasDoorKey = false. let knowsOverridePassword =  Swift 3 Logical AND OR operators These are formatted so you can copy the code straight into your Swift Playground files. //set up a bunch of conditional variables to test in our if statement that contains AND plus OR operators.

It is not possible.

From Swift grammar


if-statement → if ­if-condition­ code-block­ else-clause­opt­

if-condition → expression­ | declaration­

else-clause → else­ code-block­ | else­ if-statement­

The value of any condition in an if statement must have a type that conforms to the BooleanType protocol. The condition can also be an optional binding declaration, as discussed in Optional Binding

if-condition must be expression­ or declaration­. You can't have both expression and declaration.

let foo = bar is a declaration, it doesn't evaluate to a value that conforms to BooleanType. It declares a constant/variable foo.

Your original solution is good enough, it is much more readable then combining the conditions.

How Do I Write If Case Let in Swift?, case let immediately precedes the candidate pattern in both versions. However, when using if case let the value comes after the = operator: Using the power of switching with associated values to write elegant, logical, meaningful code  Swift provides three logical operators, AND (&&), OR(||), and NOT (! These operators are called logical operators because they evaluate upon and return Boolean value types based on logic. The three logical operators compare the bits inside their given operands, perform the operation against them, and then return the result.

How to Unwrap Multiple Optionals with One If-Let in Swift, How to Unwrap Multiple Optionals with One If-Let in Swift What I want to do right now is walk through a couple of scenarios where I unwrap Then, compare what you expected to be the print output, to the actual output to  Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) is false. || Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true. (A || B) is true.! Called Logical NOT Operator. Use to reverses the logical state of its operand.

Swift guard statement (With Examples), In this article, you will learn to use guard statement to control the flow of your program's Swift Operators · Swift Operator Precedence · Swift Ternary Operator · Swift executes statements based on certain condition (boolean value) but unlike if, the We have seen in Swift Optionals the use of if-let to unwrap an optional. Are you looking for swift online? If you are looking for swift online click.

Swift 3.0, What is difference between if let and guard in Swift?

  • It is always a good idea to provide the error messages in the question.
  • More simple statement for people who like to experiment with this: var foo : Int? = 10; if let bar = foo { if bar == 10 { println("Great success!") }}
  • The error message when using if let bar = foo && bar == 10 is Use of unresolved identifier "bar" (on the second bar, of course).
  • just a note that I was able to shorten the above example using Objective C's firstObject as follows: if let navigationController = tabBarController.viewControllers.bridgeToObjectiveC().firstObject as? UINavigationController {
  • 1. bridgeToObjectiveC is gone in beta 5 (and was quite possibly never intended for general use). 2. There's a first method on Swift's built-in Array type anyway.
  • This should be come the chosen answer.
  • yes as it's now changed. Bryan's answer was correct at that time
  • So , is for && what is there for || ?
  • @jeet.chanchawat logical OR doesn't make sense in this context. if let can only proceed if the optional successfully unwrapped and is assigned to the new variable name. If you said OR <something else> then you could easily bypass the whole purpose of the if let. For logical OR, just do a normal if and inside the body deal with the fact that the first object is still optional at that point (not unwrapped).
  • but surely "if let" - which is valid Swift syntax - is both an expression and a declaration?
  • @MaxMacLeod let foo = bar is declaration not expression. you can't do let boolValue = (let foo = bar)
  • ok but to quote the Swift guide, page 11, the example is: if let name = optionalName. optionalName must be an expression whereby if optionalName is not an optional, it evaluates to true. The second part of the statement then kicks in whereby the unwrapped optional is assigned to name. So, question is, if "optionalName is not an optional" is an expression, can it be expanded with a logical AND. Btw I think you are probably correct in that it cannot be done.
  • but you need to code to cast tabBarController again