A common feature in many languages, the Null Coalescing Operator, is a binary operator often used to shorten expressions of the type:
x = possiblyNullValue NCO valueIfNull
…where NCO
is a placeholder for the language’s null coalescing operator.
Objective C's Null Coalescing Operator is ?:
, so the expression would be:
x = possiblyNullValue ?: valueIfNull
The above expression is also equivalent to the use of tertiary operator:
x = someTestForNotNull( possiblyNullValue ) ? possiblyNullValue : valueIfNull
Advantages of a Null Coalescing Operator
- More readable code (especially with long, descriptive variable names)
- Reduced possibility of typographic errors (tested var is typed only once)
- No double evaluation of the tested variable where the tested variable is a getter, since its accessed once (or the need to cache it to intentionally avoid double evaluation).
?.
for optional values, e.g.let x = optionalObject?.value
won't cause an exception ifoptionalObject
isn't set. It will quietly not evaluate.value
and x will be an unset (i.e.nil
) optional value.