Search code examples
overridingswiftdefault-valueinstance-variablessubclassing

Overriding default value of instance var


Given class Obj,

class Obj: NSObject {
    var x = "x"
}

and its subclass, Obj1, how do you change the default value of var x?

Simply setting a new value would make the most sense, but it seems to error out...

class Obj1: Obj {
    var x = "y"
}

❗️ Cannot override with a stored property 'x'


Solution

  • Define an init() method as:

    init () {
      super.init()
      x = "y"
    }
    

    You'll want any other initializers in Obj1 to invoke this as self.init(). The Apple documentation has a long discussion on designated initializers and inheritance vis-a-vis initializers.