覆盖Swift中的存储属性 [英] Overriding a stored property in Swift
问题描述
我注意到编译器不允许我用另一个存储值覆盖存储的属性(这似乎很奇怪):
I noticed that the compiler won't let me override a stored property with another stored value (which seems odd):
class Jedi {
var lightSaberColor = "Blue"
}
class Sith: Jedi {
override var lightSaberColor = "Red" // Cannot override with a stored property lightSaberColor
}
然而,我被允许这样做计算属性:
However, I'm allowed to do this with a computed property:
class Jedi {
let lightSaberColor = "Blue"
}
class Sith: Jedi {
override var lightSaberColor : String{return "Red"}
}
为什么我不允许给它另一个值?
Why am I not allowed to give it another value?
为什么要覆盖存储的属性憎恶和计算一个犹太人?他们在想什么?
Why is overriding with a stored property an abomination and doing it with a computed one kosher? What where they thinking?
推荐答案
为什么我不允许给它另一个值?
Why am I not allowed to just give it another value?
绝对允许您为继承的属性赋予不同的值。如果在获取该初始值的构造函数中初始化该属性,并从派生类传递不同的值,则可以执行此操作:
You are definitely allowed to give an inherited property a different value. You can do it if you initialize the property in a constructor that takes that initial value, and pass a different value from the derived class:
class Jedi {
// I made lightSaberColor read-only; you can make it writable if you prefer.
let lightSaberColor : String
init(_ lsc : String = "Blue") {
lightSaberColor = lsc;
}
}
class Sith : Jedi {
init() {
super.init("Red")
}
}
let j1 = Jedi()
let j2 = Sith()
println(j1.lightSaberColor)
println(j2.lightSaberColor)
覆盖一个属性与给它一个新值不同 - 它更像是给一个一个不同的属性。事实上,当你重写计算属性时会发生这种情况:计算基类中属性的代码是替换由代码计算派生类中该属性的覆盖。
Overriding a property is not the same as giving it a new value - it is more like giving a class a different property. In fact, that is what happens when you override a computed property: the code that computes the property in the base class is replaced by code that computes the override for that property in the derived class.
[是否]可以覆盖实际的存储属性,即
lightSaberColor
还有其他的行为?
除了观察者之外,存储的属性没有行为,因此实际上没有什么可以覆盖。通过上述机制可以赋予财产不同的价值。这正是问题中的示例试图用不同的语法实现的。
Apart from observers, stored properties do not have behavior, so there is really nothing there to override. Giving the property a different value is possible through the mechanism described above. This does exactly what the example in the question is trying to achieve, with a different syntax.
这篇关于覆盖Swift中的存储属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!