Friday, July 25, 2014

Nil-coalescing Operator in Swift

Josh Smith:

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 a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

Airspeed Velocity:

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.

Leave a Comment