DEV Community

loading...

Discussion on: Ternary Unwrapping in Swift

Collapse
aidantwoods profile image
Aidan Woods

Just in an attempt at playing code golf, the int example could also be written as

let sentence = optionalNumber.map { "My favorite number is \($0)" }

Though, of course again it's specific to the second code path happening to be convenient – in general the operator will remain more useful.

One could write

let sentence = optionalNumber.map { "My favorite number is \($0)" } ?? fallback()

But I think that fails in the direction of

improve[ing] the readability of the code

So your solution wins here ;-)

Collapse
danielinoa profile image
Daniel Inoa Author

Ultimately, it's a matter of taste.
The ?? | operator, however, allows me express the same idea in the style of an operator (ternary conditional) that's already common in many programming languages.