1

CBPeripheral is a painful object to test as it can not be instanced by itself. Therefore, I'm using a wrapper (HBRPeripheralWrapper) around it (also for other purposes).

I would like to forward most of call on the wrapper (HBRPeripheralWrapper) to the actual wrapped object CBPeripheral.

It technically works using forwardInvocation but how can I adopt a similar pattern in Swift?

PS: NSInvocation is not available in 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)
  }

}
Lou Franco
  • 87,846
  • 14
  • 132
  • 192
Hugues BR
  • 2,238
  • 1
  • 20
  • 26

1 Answers1

0

Instead of making HBRPeripheralWrapper, consider extending CBPeripheral

extension CBPeripheral {
    // add whatever else you need here.
}

You don't say exactly what you do in HBRPeripheralWrapper other than forwarding, so I can't provide more help.

Lou Franco
  • 87,846
  • 14
  • 132
  • 192
  • Thx for answer. I'm wrapping rather than sub classing because I'm adding some functionality that don't make sense as subclass and also because you can't create manually `CBPeripheral` on iOS. Beside this consideration any idea how to make a nice wrapper? – Hugues BR Mar 17 '16 at 18:37
  • I'm not suggesting you subclass. Extension methods are added to any objects of the class -- even ones you don't create. Add more info about exactly what you are trying to do, and I'll add more to this answer. – Lou Franco Mar 17 '16 at 19:29
  • Oh yeah sorry. But I need storage. – Hugues BR Mar 17 '16 at 19:32
  • You can use associated objects for storage: http://stackoverflow.com/questions/24133058/is-there-a-way-to-set-associated-objects-in-swift – Lou Franco Mar 17 '16 at 19:34
  • Thx. I know about this. I would like to try a more composed solution. – Hugues BR Mar 17 '16 at 19:34
  • Also, (last but not least), I'm storing optional closure on the object, so optional closure storage on swift is pretty hardcore looking.. – Hugues BR Mar 18 '16 at 09:09