I've seen in Swift 3.1
documentation that you can include several optional bindings in an if
statement separated by commas, and that it behaves like an AND
operator.
Let's say that I have two optional properties and I'd like to check which of them (or both) is/are not nil
, unwrap the non-nil one(s), and then execute a block of code. Using this:
if let = property1, let = property2 {
// Some task to do with unwrapped property
}
only executes the if
statement block if both properties are unwrapped (AND
condition). But for me, it would be enough to have at least one of those properties being non-nil to execute the code in the if
statement block (OR
condition). But if I do like this:
if property1 != nil || property2 != nil {
// Some task to do with non-nil property
}
But then I don't have the unwrapped value of the non-nil property. I'd like to have the unwrapped value available in the if
statement block of code to avoid optional chaining there.
Which would be the best practice and most compact way to achieve this?
Unfortunately I don't think this is possible in a single line (like if let x = y || let z = a {}
). Logically it wouldn't make sense, because you would end up in a state where both variables would remain optional (if either is unwrapped, you don't know which is unwrapped or if both are). I think you'll need to take some other approach to this problem. I think the simplest form would be something like
if let unwrappedProperty1 = property1 {
handleProperty(unwrappedProperty1)
} else if let unwrappedProperty2 = property2 {
handleProperty(unwrappedProperty2)
}
or you could do something like
if let unwrappedProperty = property1 ?? property2 {
handleProperty(unwrappedProperty)
}
which would give priority to property1