在Swift中使用select器3

我在Swift 3中编写我的iOS应用程序。

我有一个UIViewController扩展,我必须检查控制器实例是否响应一个方法。 下面是我尝试的代码。

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

这里的responds(to:)方法会引发编译时错误

使用未parsing的标识符“someMethod”。

我在另一篇文章中读到,我们必须在select器参数中使用self ,但即使这样也会引发一些错误。

一个简单的解决方法:

 @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?() //... } } } 

更快一点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() //... } } } 

创build一个需要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'