I want to use an Optional variable with the ternary conditional operator but it is throwing error this error: optional cannot be used as boolean. What am I doing wrong?
To add on the already very good answers, sometimes you need the convenience of the ternary operator but also need to perform changes on the wrapped value, such as;
var fullName = lastName != nil ? "\(firsName) \(lasName!)" : firstName
But you don't want to force unwrap (even though this situation would be fine).
Then you can actually use Optional.map
:
var fullName = lastName.map({ "\(firstName) \($0)" }) ?? firstName
The completion block passed to .map
is only called if the wrapped value ($0
) is not nil
. Otherwise, that function just returns nil
, which you can then easily coalesce with the ??
operator.