arun siva
arun siva

Reputation: 869

How to write this condition using guard let

I want this condition using guard let.

if (self.fromLocation == nil || self.toLocation == nil) && self.key.isEmpty {
    return
}
print("fromLocation and toLocation are not nil and key isn't empty") 

Initially I had

guard let fromLoc = self.fromLocation, let toLoc = self.toLocation else {
    return
}
print(fromLoc,toLoc)

Now I need to continue even if one or both self.fromLocation,self.toLocation are nil only if key.isEmpty is false

The above if condition works. But how can I write this using guard let?

Condition 1. If key is empty both from and to should be not nil

Condition 2. If key is not empty from and to can be nil

Upvotes: 0

Views: 95

Answers (1)

vacawama
vacawama

Reputation: 154583

This is the equivalent guard statement:

guard (self.fromLocation != nil && self.toLocation != nil) || !self.key.isEmpty else {
    return
}

Explanation:

I arrived at this by taking the statement of when we want to return:

(self.fromLocation == nil || self.toLocation == nil) && self.key.isEmpty

and negating it to get when we want to stay:

!((self.fromLocation == nil || self.toLocation == nil) && self.key.isEmpty)

Applying De Morgan's law !(A && B) <==> !A || !B:

!(self.fromLocation == nil || self.toLocation == nil) || !self.key.isEmpty

and then applying De Morgan's law !(A || B) <==> !A && !B:

(!(self.fromLocation == nil) && !(self.toLocation) == nil) || !self.key.isEmpty

and then noting that !(A == nil) <==> A != nil gives us the final result:

(self.fromLocation != nil && self.toLocation != nil) || !self.key.isEmpty

Note:

You said you wanted to do this with guard let, but that doesn't make sense since you stated that you are willing to continue if one or both variables are nil as long as key is not empty, so it isn't possible to guarantee that the unwrapped variables will exist after the guard statement.

Upvotes: 4

Related Questions