简体   繁体   中英

Swift property observer in protocol extension?

Consider the following:

protocol ViewControllable: class {
  typealias VM: ViewModellable
  var vm: VM! { get }
  func bind()
}

extension ViewControllable {
  var vm: VM! {
    didSet {
      bind()
    }
  }
}

I'm trying to observe vm property and call bind whenever it is injected. But this doesn't compile with error saying:

Extensions may not contain stored properties

which makes sense since protocol cannot enforce properties to be stored or computed .

Is this possible to accomplish without introducing class inheritance ?

In other words, Can I observe the change of a property inside protocol extension?

No, this is explicitly disallowed. See Extension: Computed Properties :

Extensions can add new computed properties, but they cannot add stored properties, or add property observers to existing properties.

Keep in mind that if this were legal, it would add some non-trivial confusion about order of execution. Imagine there were several extensions that added didSet , and the actual implementation also had a didSet . What order should they run in? This doesn't mean it's impossible to implement, but it could be somewhat surprising if we had it.

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