Search code examples
iosswiftswift2

Optional chaining question mark after function name


I have read Optional Chaining chapter of apple's The Swift Programming Language(swift2). In this chapter, there is no mention about an optional question mark after a function name but before the left parenthesis.

But I saw the following swift code from this Apple's document (the 'Delegation' section):

 //There is a question mark right after 'window'
    if let fullScreenSize = myDelegate?.window?(myWindow, willUseFullScreenContentSize: mySize) {
        print(NSStringFromSize(fullScreenSize))
    }

What does it mean of having a question mark after a function name but before the left parenthesis ?


Solution

  • There are two situations in which this it used:

    • A protocol method is itself marked optional, so we don't know whether the adopter of the protocol implements this method.

    • We are sending a message to an AnyObject. We can send any known class message to an AnyObject — it throws away type-checking — but then, again, we don't know whether the actual object implements this method.

    So this question mark means to send this message optionally and safely. If it turns out that the recipient does not implement it, don't send the message, and return nil. If the recipient does implement it, send the message, but now we have to wrap any result in an Optional (because otherwise we could not return nil in the first case).

    Behind the scenes, Objective-C respondsToSelector: is being called. Hence, this pattern is available only if the recipient is exposed to Objective-C. Basically, this is an Objective-C language feature expressed in Swift shorthand.