Using the selector in Swift 3

I am writing my iOS application in Swift 3.

I have an extension UIViewControllerwhere I need to check if the controller instance matches the method. Below is the code I'm testing.

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

    }
}}

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

Using the unresolved identifier "someMethod".

I read in another post, we should use a selfselector inside the argument, but even this causes some error.

+4
source share
3 answers

The simplest 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 bit more swifty:

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

Create a protocol that requires someMethod()

protocol Respondable {
  func someMethod()
}

, UIViewController

extension Respondable where Self : UIViewController {

  func myMethod() {
    someMethod()
  }
}

class VC1 : UIViewController, Respondable {
  func someMethod() { print("Hello") }
}

class VC2 : UIViewController {}
class VC3 : UIViewController {}

let vc1 = VC1()
vc1.myMethod() // "Hello"

:

let vc3 = VC3()
vc3.myMethod() // error: value of type 'VC3' has no member 'myMethod'
+4

Swift 4:

If the selector is written as a string, you will not get this error.

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

        }
    }
}

And then in the viewcontroller (don't forget @objc):

@objc func someMethod() -> Void {}
0
source

Source: https://habr.com/ru/post/1656518/


All Articles