4

In Swift, is there a pattern to produce the semantic equivalent of overriding a convenience initializer?

Behaviorally, this what I'd like to do:

class MyScene: SCNScene {
   convenience init(URL url: NSURL, options: [String : AnyObject]?) {
       super.init(URL: url, options: options)

       .... other initialization
   }
}

Yes, I understand initializer chaining and why you can't actually do this directly; however, it seems like a reasonable and frequently needed behavior.

Sure, I could make my own convenience initializer which does the same thing as the superclass, and calls a designated superclass initializer. But since I'm subclassing an opaque system class, I don't necessarily know how to reconstruct the behavior.

Any way to do this or a design pattern which obviates the need for this?

Anna Dickinson
  • 3,307
  • 24
  • 43
  • You can override a convenience initialiser, you just don't need the `override` keyword. http://stackoverflow.com/questions/25322421/convenience-init-override What is your actual problem? – Paulw11 Jun 21 '16 at 23:33
  • That's not the same thing. I want to inherit the behavior of the superclass initializer, not replace it. – Anna Dickinson Jun 21 '16 at 23:37
  • You do inherit the superclass initialiser, by default, but you said you wanted to override it. I don't understand your question – Paulw11 Jun 21 '16 at 23:41
  • You don't need to know what the superclass initialiser does. You just call it via `super`. Are you perhaps getting confused by SCNScene's use of class factory methods rather than initializers? – Paulw11 Jun 21 '16 at 23:42
  • 2
    No, that's doesn't work. You can't call a convenience initializer of a superclass. In the above snippit, I would need to call a designated superclass initializer, which in this case would be `init()` or `init(coder)` – Anna Dickinson Jun 21 '16 at 23:45
  • Ok. Sorry, I get it now. No, you can't do that. You would need to set your additional properties after initialisation. – Paulw11 Jun 22 '16 at 00:05
  • Right, but you can't add properties in an extension. Currently, I'm using a factory method which does what you suggest, but it feels very clumsy. Seems like there should be some way to implement this behavior...? – Anna Dickinson Jun 22 '16 at 00:08
  • Yes, I revised my comment to remove the reference to extension. I haven't done anything with SceneKit but it looks like SCNScene is almost a "final" class – Paulw11 Jun 22 '16 at 00:10

0 Answers0