如何在 swift3 中为覆盖方法定义选择器

how to define a selector in swift3 for an override method

我想在CBPeripheralDelegate中定义一个选择器,即func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?)

在swift3中,重命名为peripheral(_: didUpdateValueFor:error),与func peripheral(peripheral: CBPeripheral, didUpdateValueForDescriptor descriptor: CBDescriptor, error: NSError?)

相同

所以当我尝试定义这样的选择器时 #selector(CBPeripheralDelegate.peripheral(_:didUpdateValueFor:error:)) 会导致编译错误:ambiguous use.

我尝试像 doc 描述的那样定义:#selector(((CBPeripheralDelegate.peripheral(_:didUpdateValueFor:error:)) as (CBPeripheralDelegate) -> (CBPeripheral, CBCharacteristic, NSError) -> Void), 也失败了。

那么在 swift3 中定义选择器的正确方法是什么?

恐怕这可能是当前 #selector 符号中的一个缺陷,您应该向 Apple or swift.org 发送错误报告。 (或者我可能只是遗漏了一些东西...)

要解决这个问题,请定义一个符合协议的 class,并定义要为其创建选择器的方法。

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

并在 #selector() 中使用 class 名称:

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

您可能已经有一个 class 实现该方法,那么您可以使用它的 class 名称。

Objective-C 选择器不保留 class 名称信息,因此,选择器可用于任何可能实现该方法的 classes。

如果你想从class里面创建一个符合协议并且有方法定义的选择器,你可以把它写成:

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