2

Task is simple: I need to create wrapper that delegates everything to wrapped object. Only the type of wrapped object is a protocol that contains optional methods. My wrapper is to implement the same protocol.

What do I do about optional methods? I can:

  1. I can implement them in my wrapper. But if they are not implemented by the object that gets wrapped what do I return from this implementations?
  2. Not implement them. In that case the wrapper object will not provide some of functionality of the wrapped object which I don't want.

Are there any better options? Please note that I am working in Swift.

nhgrif
  • 61,578
  • 25
  • 134
  • 173
Rasto
  • 17,204
  • 47
  • 154
  • 245
  • I am pretty sure you can't do that in Swift, you will need Obj-C, especially access to `NSInvocation`. Or just ignore optional methods as there are an Obj-C feature anyway. They don't exist in pure Swift. – Sulthan Jun 15 '15 at 11:56
  • I know [this answer](http://stackoverflow.com/a/18777565/2792531) is Objective-C, but for clarity, are you trying to accomplish something like this in Swift? – nhgrif Jun 15 '15 at 11:57

1 Answers1

0

You'll be using the Objective-C runtime if you are using optional methods. That means that you can query whether an object responds to an optional method, better explained here.

If you're new to the Objective-C runtime, you can read more about it at the Objective-C Runtime Programming Guide.

I think that the wrapper should check for implementation during runtime, and if missing then should return some sort of indicator, a boolean maybe, upon invocation of one of these optional methods.

Community
  • 1
  • 1
Vatsal Manot
  • 17,695
  • 9
  • 44
  • 80
  • Sure, I can detect whether the wrapped object implements optional method in runtime. By that time, however method in the wrapper is either implemented or not... That gets us to your suggestion about checking for implementation in runtime and returning bool or something. The wrapper will be visible to clients only as a protocol (same protocol as the one used as type of wrapped object). I cannot modify this protocol (part of Cocoa) so I cannot add anything to wrapper's interface. – Rasto Apr 04 '15 at 23:08