What is the opposite of if let variable { }

So you can unwrap an optional like this

if let var1 {
}
else {
}

What is the opposite for this one such that I only want to put code in the else.

Should I go with

if var1 == nil {
}

or is there something close like

if !(let var1) {

}

Thoughts?

Answered by Scott in 732636022

Fun fact: you can also refer to nil by its more formal name as an enum Optional case:

if var1 == .none {
}

Of course normally you would say nil but this form might be helpful for clarity in rare cases. And it’s fun to remember what’s really going on under the covers.

Yes the opposite is

if var1 == nil {
}

You just want to know if you can't unwrap… So test for nil.

The second form (which causes error: Cannot convert value of type '()' to expected argument type 'Bool') would not make a lot of sense: you would try to unwrap in a new var1, knowing that it fails so that you can't unwrap and create the new var1… That would be a bit bizarre, isn't it ?

Accepted Answer

Fun fact: you can also refer to nil by its more formal name as an enum Optional case:

if var1 == .none {
}

Of course normally you would say nil but this form might be helpful for clarity in rare cases. And it’s fun to remember what’s really going on under the covers.

What is the opposite of if let variable { }
 
 
Q