How do you use the Optional variable in a ternary conditional operator?

前端 未结 6 1415
深忆病人
深忆病人 2021-01-30 10:23

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?

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-30 10:52

    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.

提交回复
热议问题