Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Selector in Swift 3

Tags:

ios

swift

swift3

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.

like image 905
Adithya Avatar asked Jan 06 '23 06:01

Adithya


2 Answers

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()
            //...
        }
    }
}
like image 187
OOPer Avatar answered Jan 12 '23 04:01

OOPer


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'
like image 23
vadian Avatar answered Jan 12 '23 04:01

vadian