ABeanSits
ABeanSits

Reputation: 1725

How do I get the Nil Coalescing operator to work with closures?

let nilClosure: (() -> Void)? = nil
let notNillable: AnyObject = nilClosure ?? 1

Why does this not work? Any example showing how to get the Nil Coalescing operator to work with closures is appreciated.

The error I'm getting is:

Binary operator '??' cannot be applied to operands of type '(() -> Void)? and 'Int"'

Upvotes: 3

Views: 533

Answers (1)

Daniel T.
Daniel T.

Reputation: 33967

From Apple's docs:

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.

Note that last sentence...

And even then the ?? operator doesn't work with closures. And even if it did, closures don't conform to AnyObject and so can't be assigned to one.

You can do this:

enum OddObject {
    case Closure(() -> Void)
    case Value(Int)
}

let wrappedNilClosure: OddObject? = nil
let oddObject = wrappedNilClosure ?? .Value(1)

Or this:

let nilClosure: (() -> Void)? = nil
let notNillable: Any = nilClosure != nil ? nilClosure! : { }

It depends on what need you are trying to fill.

Upvotes: 6

Related Questions