DEV Community


Discussion on: Ternary Unwrapping in Swift

aidantwoods profile image
Aidan Woods

Of course you can put arbitrary functions in either, so in general this operator will be useful – but when both code paths differ only in data you can reduce to a nil-coalescing though. E.g. the initial example can be written as ;-)

let foo = Foo(optionalDependency ?? fallback)
aidantwoods profile image
Aidan Woods

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

let sentence = { "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 = { "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 ;-)

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.