DEV Community

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)" }
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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

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.

Collapse
 
eric_summers_0b8bd15160d8 profile image
Eric Summers

Using map in this way is documented for this use in the standard library, so I prefer that method.