48

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).
1
  • As far as I can see, the closest thing it's got is ?. for optional values, e.g. let x = optionalObject?.value won't cause an exception if optionalObject isn't set. It will quietly not evaluate .value and x will be an unset (i.e. nil) optional value. Jun 6, 2014 at 13:57

6 Answers 6

57

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
3
  • 1
    The x ?? y ?? 1 did not work as you would expect in beta 5 (it would return x), but as of beta 6 it works (returning y in this case, or 1 if y were nil too). Aug 19, 2014 at 7:46
  • Also, here's a nil coalescing compound assignment operator x ??= y: gist.github.com/268694f46ec8c135923c
    – user246672
    Jun 12, 2015 at 0:37
  • Sorry if this is plainly obvious, but could you please tell me what the difference between using || and ?? in that case would be? Dec 1, 2015 at 15:27
16

(Also see blog post)

No, Swift doesn't currently support a null coalescing operator.

Defining Custom Null Coalescing Operator for Swift

A custom operator can be defined for Swift, with the following considerations regarding the Swift language:

Swift and Nil

Swift supports a null concept through its Optional type (a Discriminated Union of sorts) which either holds a value of the underlying type or no value (indicated by nil) and must be explicitly defined as being optional:

var a : String?

A non-optional type can never be nil, or assigned nil. Therefore a custom infix binary NCO can be expected to take an optional as its first parameter.

Available Characters for Custom Operators in Swift

In Swift, custom operators can be comprised of the following characters only:

/ = - + * % < > ! & | ^ . ~

The Operator

Given the choice of available characters, ||| (three pipes, no spacing) isn't terrible (similar to the double pipe OR in Javascript which is used like a NCO):

Using the Operator

var a = String?
var z = a ||| "it's nil!"
println(z) //Output: it's nil!

Defining the Operator

operator infix ||| {}

@infix func |||<T> (left: T?, right: T) -> T  {
  if let l = left { return l }
  return right
}
3
  • Nice use of a custom binary operator, +1
    – user2742371
    Jun 6, 2014 at 14:03
  • 5
    Suggestion: add associativity left inside the operator declaration so that you can type: let x = foo ||| bar ||| baz ||| "it's nil"
    – Jason
    Jun 9, 2014 at 11:03
  • 1
    I'm trying to understand why it actually accepts two optionals, like in optInt1 ||| optInt2 returning nil if both are nil or {some x} if one equals x. It seems like when the rhs is an optional, the T type becomes an optional itself.
    – Teejay
    Jun 29, 2014 at 16:35
8

What Venkat says is correct: there is none but you can define one. His implementation however is not ideal because he forgot to use @auto_closure.

Also I believe you can overload || without needing to define a new operator.

I do not have the compiler here, but I'll try to give you the code from memory:

func |||<T> (maybe: Optional<T>, defaultValue: @auto_closure () -> T) -> T {
    if let some = maybe { 
      return some 
    }
    return defaultValue()
}

Edit: Thanks to Martin R for testing this with the compiler. See the comments. Apparently overloading || is possible but may not work as expected because of the way Swift handles resolution of overloaded operators (which is undocumented and therefore I have no idea if it can be worked around or not). I've changed the function above to use |||.

10
  • At least in the Playground, a || "it's nil!" returns true, even with your overloaded definition. It works as expected if your operator is called |||.
    – Martin R
    Jun 6, 2014 at 14:12
  • Interesting. It does not error on the overloaded definition, but it does not use it. Unfortunately there's no documentation that explains formally how Swift resolves overloads. If you have the compiler at hand you may try some experiments, or we can wait for more documentation from Apple. For the moment just go with a custom operator. I'll edit the answer to reflect your findings. Jun 6, 2014 at 14:17
  • Same result in a compiled app.
    – Martin R
    Jun 6, 2014 at 16:00
  • 1
    @Teejay His implementation is strict in both arguments, mine is only strict in the first argument. You would expect this sort of operator to have lazy semantics at least in the second argument (also known as "short circuiting") and not compute the default value at all, if there already is a value. This is what I do, he doesn't. Jun 30, 2014 at 5:58
  • 1
    @Teejay It is for automatically creating a closure surrounding the argument. And that is exactly how short circuit is implemented in applicative order languages. Instead of passing a value, which in applicative order makes the computation strict, you create a closure which may be lazily evaluated. Jun 30, 2014 at 7:58
2

I blogged about a custom operator function that provides nil-coalescing here: http://ijoshsmith.com/2014/07/24/nil-coalescing-operator-in-swift/

My choice of operator was !! which combines the logical not operator (!) and the unwrap operator (!) for a "if cannot unwrap" semantic. Seems I was late to the party, given this thread is already over a month old. Either way, here's my implementation in case you're interested...

operator infix !! {}

@infix func !! <T> (
    value: T?,
    defaultValue: @auto_closure () -> T)
    -> T
{
    return value ? value! : defaultValue()
}
0

You can check with playground code below.

import UIKit
var personalSite : String?
let defaultSite = "http://www.google.com"

var website = personalSite ?? defaultSite
0

hope this will help you

  1. yes , Now it is added in swift

  2. little Explanation

           var anumber:Int? = someValue
           var banumber = 2
           anumber =   ( anumber != nil) ? anumber : banumber ------- (a)
           println(anumber!)
    

now instead of writing all (a) this we can just use this ->

        anumber = anumber ?? banumber

and

The operator can also be used multiple times in the same expression. like

     firstNumber ?? secondNumber ?? thirdNumber. 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.