Jaehoon Lee Jaehoon Lee - 1 year ago 59
Swift Question

Swift property observing doesn't override

I wrote class inheritance with property override. I found stored property observing doesn't work like other overriding.

These classes have stored property and calculated property for compare.

class Parent {
var storedProp : Int! {
didSet {
print("Parent stored property didSet")
var calcProp : Int {
print("Parent calculated property get")
return 100

class Child : Parent {
override var storedProp : Int! {
didSet {
print("Child stored property didSet")

override var calcProp : Int {
print("Child calculated property get")
return 101

When I instantiate Child object and get calculated property. Property in child class override and doesn't work parent's.

var obj = Child()
let value = obj.calcProp

I expected same thing happen on property observing, but property observing of child and parent both works. It looks like propagated.

obj.storedProp = 999

// Parent stored property didSet
// Child stored property didSet

Is it intended?.. and How can i prevent the propagation?

Answer Source

Inheritance section of The Swift Programming Language (Swift 2.2) describes 'overriding property observers' as 'adding property observers'

Overriding Property Observers

You can use property overriding to add property observers to an inherited property...

If a subclass were able to override didSet observer of currentSpeed property of AutomaticCar class in the following example:

class AutomaticCar {
    var currentSpeed: Double {
        didSet {
            gear = Int(currentSpeed / 10.0) + 1

The didSet in the subclass would prevent updating gear property which could break the designed behavior of the super class, AutomaticCar.