Search code examples
swiftoptional-binding

How to check multiple values in negative expression with optional binding?


I want to check if two optional variables are all null. For example, in C,

int n1 = 1;
int n2 = 2;
if( n1!=0 && n2!=0 ) {
     //  do something.
}

Is there any way to do this in Swift?


Solution

  • Just use the && operator:

    // here are the optional variables:
    var a: Int? = nil
    var b: Int? = nil
    
    if a == nil && b == nil {
        // this will only run if both a and b are nil
    }