0

You can only use the computed variable with both setter and getter to overriding the stored property of the superclass. I got this conclusion by trying the following code. I'm not sure I'm 100% correct. Please correct me if I'm wrong. Thanks!

class SuperClass {
    var ID = 2202
}

//Wrong
class SubClass: SuperClass {
    override var ID = 2203
}

//worng
class SubClass: SuperClass {
    override var ID: Int {
        return super.ID + 1
    }
}

//Correct
class SubClass: SuperClass {
    override var ID: Int {
        get {
            return super.ID + 1
        }
        set {

        }
    }
}
SLN
  • 4,772
  • 2
  • 38
  • 79
  • 1
    Your superclass states that objects of it contains a _mutable_ property `ID`. Since suberclass objects are interchangeable with subclass objects, subclass objects must contain a property `ID` that is _mutable_ (even if we use a "dummy" setter as in your example above: not actually mutating the value). This is obvious if you attempt to pass a subclass object to e.g. `func foo(bar: SuperClass) { bar.ID = 42 }`; if the subclass would be allowed to override `ID` with only a getter, then calling `foo(...)` with such objects would not make much sense. – dfrib Jun 26 '16 at 20:21
  • 1
    ... see also the following Q&A:s: [Overriding a stored property in Swift](http://stackoverflow.com/questions/26691935/overriding-a-stored-property-in-swift), [Overriding superclass property with different type in Swift](http://stackoverflow.com/questions/24094158/overriding-superclass-property-with-different-type-in-swift). – dfrib Jun 26 '16 at 20:25

1 Answers1

1

You cannot override a stored property of the superclass, but you can change its value from the subclass:

class SuperClass {
    var ID = 2202
}

class SubClass: SuperClass {
    override init() {
        super.init()
        self.ID = 2203
    }
}

let a = SuperClass()
let b = SubClass()

print(a.ID)
print(b.ID)
Mike Henderson
  • 2,028
  • 1
  • 13
  • 32