0

I would like to do something similar to the following with an NSObject subclass

class Thing: NSObject {
  class func defaultText() -> String { ... }

  let text: String

  init(text: String?) {
    self.text = text ?? self.dynamicType.defaultText() // Of course, this line won't compile
    super.init()
  }
}

so that Thing subclasses may override defaultText() without requiring them to override the initializer. This is easy to do with a mutable stored property, but it would be nice to have it constant. Is there a way to do this?

This is a separate issue than overriding static vars in subclasses swift 1.2 . There is no desire to override a constant or a static method. The only thing in question is, in the initializer where the constant is set, is there a way to compute a value based on the specific class that is being initialized?

Community
  • 1
  • 1
Charles
  • 1
  • 2
  • You can't override a constant. It is *constant*. Also see: http://stackoverflow.com/questions/29189700/overriding-static-vars-in-subclasses-swift-1-2 – Ozgur Vatansever Apr 29 '16 at 20:01
  • Actually, the question is regarding how I can override the computed value of the expression on the right hand of where it is set. – Charles Apr 29 '16 at 20:09
  • Then you need to override `defaultText` method in the subclass: `class override func defaultText() { ... }`. You can't update/override the constant used in `defaultText` from within the subclass. – Ozgur Vatansever Apr 29 '16 at 20:12
  • @ogzur What? `self.dynamicType.defaultText()` is not going to compile because it is using `self` before calling the superclass initializer. The issue is not trying to override a class method in the same class, the issue is understanding if or how to determine the dynamic type of `self` before the superclass initializer, or if there is a similar approach to allow a subclass to optionally decide to override certain default values. – Charles Apr 29 '16 at 20:16

0 Answers0