协议扩展中的Swift属性观察器? [英] Swift property observer in protocol extension?

查看:183
本文介绍了协议扩展中的Swift属性观察器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

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

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

我试图观察vm属性,并在每次注入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

很有意义,因为协议不能将属性强制为storedcomputed.

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

是否可以在不引入class inheritance的情况下完成?

Is this possible to accomplish without introducing class inheritance?

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

推荐答案

否,这是明确不允许的.参见扩展:计算属性:

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.

请记住,如果这是合法的,则会对执行顺序造成一些不小的混乱.想象有几个扩展添加了didSet,并且实际的实现中也有一个didSet.他们应该以什么顺序运行?这并不意味着不可能实现,但是如果我们拥有它,可能会有些令人惊讶.

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.

这篇关于协议扩展中的Swift属性观察器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆