Jaehoon Lee
Jaehoon Lee

Reputation: 33

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?

Upvotes: 3

Views: 1779

Answers (2)

Simon
Simon

Reputation: 149

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.

Upvotes: 3

Vince O'Sullivan
Vince O'Sullivan

Reputation: 2701

Property observers observe and respond to changes in a property’s value. There are two observers willSet and didSet. There are no observers for getting a property (i.e. no willGet and no didGet).

In your calcProp property definitions, you have overridden the get computed property not the (non-existant) didGet property observer. Your call to get a value from the child, calls only the get method on the child's property. Neither the child nor the parent is observing the get.

To prevent the effect you are seeing: when setting a property you should be implementing the set computed property. You must remove the didSet observer from parent if you don't wan't it to observe changes in that value even when the change is originating in a child.

Upvotes: 1

Related Questions