Adithya Adithya - 2 months ago 29
Swift Question

Using Selector in Swift 3

I am writing my iOS Application in Swift 3.

I have a

UIViewController
extension, where I have to check if the controller instance responds to a method. Below is the code that I a trying out.

extension UIViewController {
func myMethod() {
if self.responds(to: #selector(someMethod)) {

}
}}


Here the
responds(to:)
method throws a compile time error


Use of unresolved identifier "someMethod".


I read in another post, we have to use
self
inside the selector argument, but even that is throwing some error.

Answer

A simple workaround:

@objc protocol SomeMethodType {
    func someMethod()
}
extension UIViewController {
    func myMethod() {
        if self.responds(to: #selector(SomeMethodType.someMethod)) {
            //...
            self.perform(#selector(SomeMethodType.someMethod))
            // or
            (self as AnyObject).someMethod?()
            //...
        }
    }
}

A little more Swifty way:

protocol SomeMethodType {
    func someMethod()
}
//For all classes implementing `someMethod()`.
extension MyViewController: SomeMethodType {}
//...
extension UIViewController {
    func myMethod() {
        if let someMethodSelf = self as? SomeMethodType {
            //...
            someMethodSelf.someMethod()
            //...
        }
    }
}