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 ;-)
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.
?? |
Using map in this way is documented for this use in the standard library, so I prefer that method.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Just in an attempt at playing code golf, the int example could also be written as
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
But I think that fails in the direction of
So your solution wins here ;-)
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.Using map in this way is documented for this use in the standard library, so I prefer that method.