Check if function exists in Swift

I want to check if func function exists before I call it. For example:

if let touch: AnyObject = touches.anyObject() { let location = touch.locationInView(self) touchMoved(Int(location.x), Int(location.y)) } 

I would call touchMoved (Int, Int) if it exists. Is it possible?

+4
swift func
source share
1 answer

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?() //Returns "aRandomFunc" (instance as AnyObject).anotherRandomFunction?() //Returns nil, as it is not implemented 

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.

+3
source share

All Articles