Optional chaining question mark after function name

I read the optional apple chapter chain . Swift language for programming (swift2). In this chapter, there is no mention of an optional question mark after the function name, but before the left bracket.

But I saw the following quick code from this Apple Document (Delegation section):

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

What does the question mark mean after the function name, but before the left bracket?

+5
source share
2 answers

There are two situations in which this was used:

  • The protocol method itself is marked optional , so we don’t know whether this method implements the protocol.

  • We send a message to AnyObject. We can send any known message of the AnyObject class - it cancels the type checking, but then we still do not know whether this object implements this method.

So, this question mark means sending this message arbitrarily and safely. If it turns out that the recipient does not implement it, do not send a message or return zero. If the recipient executes it, send a message, but now we must wrap any result in Optional (since otherwise we could not return nil in the first case).

Behind the scenes, Objective-C respondsToSelector: called. Therefore, this template is only available if the receiver is exposed to Objective-C. This is mainly an Objective-C language function, expressed in abbreviated abbreviated form.

+9
source

This is used when the protocol method is optional and may not be implemented on the object. (In this case, the optional window:willUseFullScreenContentSize: method from the NSWindowDelegate protocol)

0
source

All Articles