A O A O - 3 years ago 78
Swift Question

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?

Answer Source

You can do it this way:

if let popupButton = result?.control as? NSPopUpButton, popupButton.numberOfItems <= 1 {
    //blahblah
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download