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

158 Views Asked by At

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?

3

There are 3 best solutions below

1
Sweeper On BEST ANSWER

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
}
1
Robert Dresler On

What you call optional binding is actually just if statement with multiple conditions. Optional binding is used when you want to define constant/variable from constant/variable which can be nil. When isn't, code inside if statement gets executed.

But you need to define two values with optional type. This you can do with question mark Type? and then you can check if both values aren't nil.

Your code in Swift:

let n1: Int? = 1
let n2: Int? = 2
if n1 == nil && n2 == nil {
    //  do something.
}
0
ielyamani On

You can check if two optionals are nil by comparaing them to nil

let n1: Int? = nil
let n2: Int? = nil
if n1 == nil, n2 == nil {
    print("Nil all the way")
}

Separating conditions with a comma is equivalent to using &&.

Here is an alternative using tuples:

if (n1, n2) == (nil, nil) {
    print("Nil all the way")
}