ThomasB
ThomasB

Reputation: 41

What is the role of the nil-coalescing operator "??" in optional chaining?

I don't understand what the ?? operator does in the second line of this fragment:

    func presentingControllerFrameWithContext(_ transitionContext: AnyObject) -> CGRect {
        let frame = transitionContext.containerView??.bounds
        // more code
    }

I'm new to Swift and have to maintain/extend existing code. I used many resources but was not able to find an explanation of this usage of the ?? operator, which I think I understand as explained in:
https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html#ID72

As stated in the title of this post, I assume it is some special case of optional chaining as explained in:
https://docs.swift.org/swift-book/LanguageGuide/OptionalChaining.html#ID246

But I cannot find any usage of ?? there and perhaps my assumption is totally wrong...

I hope somebody here can give me an explanation or a hint where to look for an answer.

Upvotes: 1

Views: 382

Answers (1)

David Pasztor
David Pasztor

Reputation: 54745

That's not the nil-coalescing operator you are seeing. The nil-coalescing operator is a binary operator, that needs to be placed between an Optional value and a non-Optional one or two Optional values. In your code example, that's clearly not the case.

What you are seeing is optional chaining on a nested-Optional.

let nestedOptional: Int?? = nil

nestedOptional??.description

You can create Optional values whose wrapped value is also an Optional, in which case you need to unwrap each optional layer one-by-one.

Upvotes: 3

Related Questions