You can use the optional chain operator:
It seems like this only works with ObjC protocols that define @optional functions. It also seems like you need to apply to AnyObject:
import Cocoa @objc protocol SomeRandomProtocol { @optional func aRandomFunction() -> String @optional func anotherRandomFunction() -> String } class SomeRandomClass : NSObject { func aRandomFunction() -> String { return "aRandomFunc" } } var instance = SomeRandomClass() (instance as AnyObject).aRandomFunction?()
It is strange that in the above example the protocol "SomeRandomProtocol" is not even declared for "SomeRandomClass" ... but without defining the protocol, the chain operator gives an error - at least on the playground. It seems that the compiler needs a prototype of the function declared earlier for the operator? ().
It looks like maybe there are some bugs or work.
See the “Quick Depth Compatibility” section for more information on the optional chain operator and how it works in this case.
Jake
source share