As mentioned, in Swift most of the time you can achieve what you need with the ?
optional unwrapper operator. This allows you to call a method on an object if and only if the object exists (not nil
) and the method is implemented.
In the case where you still need respondsToSelector:
, it is still there as part of the NSObject
protocol.
If you are calling respondsToSelector:
on an Obj-C type in Swift, then it works the same as you would expect. If you are using it on your own Swift class, you will need to ensure your class derives from NSObject
.
Here’s an example of a Swift class that you can check if it responds to a selector:
class Worker : NSObject
{
func work() { }
func eat(food: AnyObject) { }
func sleep(hours: Int, minutes: Int) { }
}
let worker = Worker()
let canWork = worker.respondsToSelector(Selector("work")) // true
let canEat = worker.respondsToSelector(Selector("eat:")) // true
let canSleep = worker.respondsToSelector(Selector("sleep:minutes:")) // true
let canQuit = worker.respondsToSelector(Selector("quit")) // false
It is important that you do not leave out the parameter names. In this example, Selector("sleep::")
is not the same as Selector("sleep:minutes:")
.