As seen in the last example above, I created a custom operator function, dubbed the nil-coalescing operator. That operator function evaluates to an optional’s value unless it is nil, in which case it evaluates to a fallback/default value. This is based on the null-coalescing operator in C#, which is formed by two adjacent question marks (??). Since Swift does not allow custom operator functions to include a question mark, I instead opted for two adjacent exclamation marks (!!). I think of it as “If the optional cannot be unwrapped (because it’s nil), then use this value instead.”
Update (2014-08-17): As of beta 5, Swift now has nil-coalescing operator:
The nil coalescing operator (
a ?? b) unwraps an optional
aif it contains a value, or returns a default value
nil. The expression
ais always of an optional type. The expression
bmust match the type that is stored inside
Is this behaviour of
??a bug? I dunno, probably not. You could prefer it to behave like the raw ternary operator, or fail to compile by somehow mandating the right-hand type really be what’s contained in the left-hand optional. But you could also say it’s behaving correctly, based on how the language works, and you might even need it to behave this way in some scenarios.
Either way, it’s a useful case study if you plan on implementing a generic function that takes optionals yourself.
Stay up-to-date by subscribing to the Comments RSS Feed for this post.