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
The nullish coalescing operator ( ?? ) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined , and otherwise returns its left-hand side operand.
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.
A null-coalescing operator is used to check such a variable (of nullable type) for null. If the variable is null, the null-coalescing operator is used to supply the default value while assigning to a variable of non-nullable type.
As of Swift 2.2 (Xcode 6, beta 5) it's ??
var x: Int? var y: Int? = 8 var z: Int = x ?? 9000 // z == 9000 z = y ?? 9001 // z == 8
a ?? b
is equivalent to the following code:
a != nil ? a! : b
And as of Beta 6, you can do this:
x ?? y ?? 1 == 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With