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.
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()
            //...
        }
    }
}
                        Create a protocol which requires someMethod()
protocol Respondable {
  func someMethod()
}
And a protocol extension which affects only UIViewController instances
extension Respondable where Self : UIViewController {
  func myMethod() {
    someMethod()
  }
}
Adopt the protocol to some of the view controllers
class VC1 : UIViewController, Respondable {
  func someMethod() { print("Hello") }
}
class VC2 : UIViewController {}
class VC3 : UIViewController {}
Now call the method in the extension
let vc1 = VC1()
vc1.myMethod() // "Hello"
Otherwise you get a compiler error:
let vc3 = VC3()
vc3.myMethod() // error: value of type 'VC3' has no member 'myMethod'
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With