Nil-coalescing Operator in Swift
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 optionala
if it contains a value, or returns a default valueb
ifa
isnil
. The expressiona
is always of an optional type. The expressionb
must match the type that is stored insidea
.
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.
1 Comment RSS · Twitter
While this is cool, it also seems to get at the fear many have of operator overloading. That is creating symbolic entities that are completely non-obvious in function to people reading source code. At least the Apple ! is standard enough that people reading your code know to look in Swift documentation.