简体   繁体   中英

Swift: property observers for computed properties

As far as I know, Swift allows us to set property observers for either stored and computed properties. But if computed property value depends on some backing store, property observers are not fired when these backing store values are changed:

public class BaseClass {
    private var privateVar1: Int = 0
    private var privateVar2: Int = 0
    public var property: Int {
        get {
            return privateVar1 * privateVar2
        }
        set {
            print("some setter without effect")
        }
    }
    private func changeSomeValues() {
        privateVar1 = 1
        privateVar2 = 2
    } 
}

public class SubClass : BaseClass {
    override var property: Int {
        didSet {
            print("didSet \(property)")
        }
    }
}

didSet of SubClass isn't called when changeSomeValues is called.

Let's consider a case: we have such BaseClass in a third-party framework. We define SubClass in our app. The question is: how can we rely on SubClass observers without knowledge about property nature: is it stored (and we can rely on observers) or computed (and then we can't expect firing observers each time when we expect it)? Is it possible? If no, is it an incapsulation violation?

That behaviour is perfectly normal. There is no way for the compiler to know which backing store really corresponds to which computed property. Your backing store in this case is made up of private variables that will not be accessible outside the class itself. So the only place where an "under the hood" change can occur is in the base class. It is that class's prerogative to use its calculated properties (which will trigger the observers) or the backstore (which will not).

In your example, assuming you never want to allow "invisible" changes, the changeSomeValues() function is breaking its own rules and not respecting the contract it promised to its subclasses and callers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM