Whats the best way to execute code if some optional isn't nil? Clearly, the most obvious way to do it would be to directly check if the value is nil:
if optionalValue != nil {
//Execute code
}
I've also seen the following:
if let _ = optionalValue {
//Execute code
}
The second one seems more in line with swift since it's using optional chaining. Are there any advantages to using one method over the other? Is there a better way to do it? By better I mean "more in line with Swift", whatever that means.
Optional binding should be used if you actually need the unwrapped value. It is a shortcut for a longer expression, and I think it should be thought in those terms. In fact, in swift 1.2 this optional binding expression:
if let unwrapped = optional {
println("Use the unwrapped value \(unwrapped)")
}
is syntactic sugar for code like this (remember that optionals are, under the hood, instances of an Optional<T>
enumeration):
switch optional {
case .Some(let unwrapped):
println("Use the unwrapped value \(unwrapped)")
case .None:
break
}
Using an optional binding and not assigning the unwrapped value to a variable is like having a box which may contain a TV inside. You don't remove the TV from the box if your purpose is to verify whether the box is empty or not - you just open the box and look inside.
So, if you need to execute some code if a variable is not nil, but you don't need nor use the actual value contained in the optional variable, then the not-nil check is, in my opinion, the best way to do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With