Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Swift have a null coalescing operator and if not, what is an example of a custom operator?

Tags:

swift

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).
like image 215
Venkat Peri Avatar asked Jun 06 '14 13:06

Venkat Peri


People also ask

Which of the following is null coalescing operator?

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.

What is the nil-coalescing operator in Swift?

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.

What is a null coalescing operator used for?

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.


1 Answers

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 
like image 128
Jiaaro Avatar answered Oct 12 '22 04:10

Jiaaro