30

考虑以下:

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

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

我正在尝试观察vm属性并bind在注入时调用。但这不会编译错误说:

扩展可能不包含存储的属性

这是有道理的,因为协议不能强制属性为storedor computed

这可以在不引入的情况下完成class inheritance吗?

换句话说,我可以观察协议扩展内的属性变化吗?

4

1 回答 1

35

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.

于 2015-11-23T04:27:33.947 回答