Swift Optionals and String Interpolation
Do you know this problem? You want to display an optional value in the UI or log it to the console for debugging, but you don’t like the default string conversion for optionals, which results in either
"Optional(…)"
or"nil"
.[…]
The problem with the third option is that the nil-coalescing operator
??
requires matching types — if the left operand is aT?
, the right operand must be aT
. Applied to the example above, this means I can provide anotherInt
as a default value, but not a string — which is what I’d like to do in this situation.[…]
I solved this by defining my own custom optional-string-coalescing operator.