Search code examples
swiftif-statementoptional-binding

Is it possible to use the variable from an optional binding within the same conditional statement?


if let popupButton = result?.control as? NSPopUpButto {
    if popupButton.numberOfItems <= 1 {
        // blahblah
    }
}

I want to avoid the double nested if.

if let popupButton = result?.control as? NSPopUpButton && popupButton.numberOfItems <= 1 {}

but I get the unresolved identifier compiler error if I do that.

Is there any way to make this condition on one line? Or because I'm using an optional binding, am I forced to make a nested if here?


Solution

  • You can do it this way:

    if let popupButton = result?.control as? NSPopUpButton, popupButton.numberOfItems <= 1 {
        //blahblah
    }