30

次の点を考慮してください。

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

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

vmプロパティを観察し、bind注入されるたびに呼び出すようにしています。しかし、これは次のようなエラーでコンパイルされません:

拡張機能には保存されたプロパティが含まれていない可能性があります

storedプロトコルはプロパティをorにすることを強制できないため、これは理にかなっています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 に答える