luffy
luffy

Reputation: 429

how to define a selector in swift3 for an override method

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?

Upvotes: 0

Views: 409

Answers (1)

OOPer
OOPer

Reputation: 47896

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:))

Upvotes: 1

Related Questions