Wednesday, December 7, 2016

Swift Optionals and String Interpolation

Ole Begemann:

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 a T?, the right operand must be a T. Applied to the example above, this means I can provide another Int 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.

Comments RSS · Twitter

Leave a Comment