Swift reverse nil-coalescenting operator?

Viewed 103

Swift has the nil-coalescing operator a ?? b which is shorthand for a != nil ? a : b. Does Swift have the opposite operator, a shorthand for a == nil ? a : b or in other words, a == nil ? nil : b?

I would use it to map an optional value to something else, like so:

let x = dict["key"] != nil ? mapValue(dict["key"]) : nil
// ideally: let x = dict["key"] ¿¿ mapValue(dict["key"])
1 Answers

dict["key"] returns an optional, and you want to map that value to another value if it is present, or get nil otherwise. That is exactly what Optional.map() is for:

Evaluates the given closure when this Optional instance is not nil, passing the unwrapped value as a parameter.

In your case:

let x = dict["key"].map { mapValue($0) }

or simply

let x = dict["key"].map(mapValue)

This also has the advantage over

let x = dict["key"] != nil ? mapValue(dict["key"]) : nil
// or the hypothetical
let x = dict["key"] ¿¿ mapValue(dict["key"])

that dict["key"] is evaluated only once, not twice.

Related