how to define a selector in swift3 for an override method

帅比萌擦擦* 提交于 2019-12-25 09:15:30

问题


I want to define a selector in CBPeripheralDelegate, which is func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?).

In swift3, it is renamed to peripheral(_: didUpdateValueFor:error), and it is same as the func peripheral(peripheral: CBPeripheral, didUpdateValueForDescriptor descriptor: CBDescriptor, error: NSError?)

So when I try to define a selector like this #selector(CBPeripheralDelegate.peripheral(_:didUpdateValueFor:error:)) will cause a compile error: ambiguous use.

And I try to define like the doc describe: #selector(((CBPeripheralDelegate.peripheral(_:didUpdateValueFor:error:)) as (CBPeripheralDelegate) -> (CBPeripheral, CBCharacteristic, NSError) -> Void), failed either.

So what is the right way to define a selector in swift3?


回答1:


I'm afraid this may be a flaw in the current #selector notation and you should send a bug report to Apple or swift.org. (Or I may be just missing something...)

To work this around, define a class conforming to the protocol, and define the method that you want to make a selector for.

class TheClass: NSObject, CBPeripheralDelegate {
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        //No need to actually implement the method
    }
}

And use that class name in your #selector():

#selector(TheClass.peripheral(_:didUpdateValueFor:error:))

You may already have a class implementing the method, then you can use the class name of it.

Objective-C selectors does not keep a class name information, so, the selector can be used for any classes which may be implementing the method.

If you want to make a selector from inside a class which conforms the protocol and has a definition for the method, you can write it as:

#selector(peripheral(_:didUpdateValueFor:error:))


来源:https://stackoverflow.com/questions/39221563/how-to-define-a-selector-in-swift3-for-an-override-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!