且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift重写实例变量

更新时间:2023-02-26 19:32:58

不能简单地重新定义一个子类中的常量(毕竟它是一个常量)。您得到的错误是无法覆盖与存储属性。它似乎可以覆盖 var ,但是,当我改变 let someVariable var someVariable 当我在子类中访问它时,我得到了someVariable的不确定的使用(注意 - 不管我使用 override 或不)。

As you say, you cannot simply redefine a constant in a subclass (it is a constant, after all). The error you get is "Cannot override with a stored property". It does appear to be possible to override a var, however, when I change the let someVariable to var someVariable I get "ambiguous use of 'someVariable'" when I access it in the subclass (note - same thing happens whether I use override or not).

最初的顾问建议的最简单的解决方案是使用getter。这真的是一个函数,所以你可以高兴地覆盖它,支持变量将为你管理,如果你不提供一个setter,它将是常数:

The simplest solution, as your initial advisors suggested, is to use a getter. This is really a function, so you can happily override it, the backing variable will be managed for you, and if you don't supply a setter, it will be constant:

class BaseView: UIView {
    var someVariable: Int { get { return 1 } }
    // do some work with someVariable
}

class ExtendedView: BaseView {
    override var someVariable: Int { get { return 2 } }
}

let a = BaseView()
a.someVariable // 1
let b = ExtendedView()
b.someVariable // 2