Swift中的对象包装器(代理)转发方法

时间:2016-03-16 20:52:57

标签: swift wrapper

CBPeripheral是一个痛苦的测试对象,因为它本身无法实例化。因此,我在它周围使用包装器(HBRPeripheralWrapper)(也用于其他目的)。

我想转发包装器上的大部分调用 (HBRPeripheralWrapper)到实际包装的对象CBPeripheral

技术上可以使用forwardInvocation,但我怎样才能在Swift中采用类似的模式?

PS:NSInvocation

中无法使用Swift
class HBRPeripheralWrapper {
  let peripheral:CBPeripheral

  // I would like to avoid this "manual" forwarding
  var identifier: NSUUID {
      get {
          return peripheral.identifier
      }
  }

  init(peripheral:CBPeripheral) {
    self.peripheral = peripheral
  }

  // target forwarding is great, but how can I make the compiler happy?
  override func forwardingTargetForSelector(aSelector: Selector) -> AnyObject? {
    if(self.peripheral.respondsToSelector(aSelector)) {
      return self.peripheral
    }
    return super.forwardingTargetForSelector(aSelector)
  }

}

1 个答案:

答案 0 :(得分:0)

请考虑延长HBRPeripheralWrapper

,而不是CBPeripheral
extension CBPeripheral {
    // add whatever else you need here.
}

除了转发之外,你没有准确说明你在HBRPeripheralWrapper做了什么,所以我无法提供更多帮助。