为在Swift中使用的Objective-C类添加一个便利初始化程序扩展

时间:2016-05-10 05:28:03

标签: ios objective-c swift

我使用iOS-nRF-Toolbox

中的一些代码

class ScannedPeripheral包含初始化程序

+ (ScannedPeripheral*) initWithPeripheral:(CBPeripheral*)peripheral rssi:(int)RSSI isPeripheralConnected:(BOOL)isConnected NS_REFINED_FOR_SWIFT;

我可以像这样在Swift中调用它

ScannedPeripheral.initWithPeripheral(peripheral, rssi: 0, isPeripheralConnected: true)

但它并不好看。 Apple如何采用其Cocoa API?

我尝试使用NS_REFINED_FOR_SWIFT标记初始化程序并添加Swift扩展名:

extension ScannedPeripheral {
    convenience init(peripheral: CBPeripheral, rssi: Int32, isPeripheralConnected: Bool) {
        ScannedPeripheral.__initWithPeripheral(peripheral, rssi: rssi, isPeripheralConnected: isPeripheralConnected);
    }
}

但现在错误显示Self.init isn't called on all paths before returning from initializer

1 个答案:

答案 0 :(得分:1)

我认为最好为ScannedPeripheral创建子类而不是扩展,因为扩展可能不支持初始化和覆盖方法。

例子

class SubClassScannedPeripheral: ScannedPeripheral {
  override class func initWithPeripheral(peripheral: CBPeripheral, rssi: Int32, isPeripheralConnected: Bool) -> ScannedPeripheral {
   return ScannedPeripheral.initWithPeripheral(peripheral, rssi: rssi, isPeripheralConnected: isPeripheralConnected);
}
}