覆盖 Swift 中的存储属性 [英] Overriding a stored property in Swift

查看:31
本文介绍了覆盖 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?

[Is it] possible to override the actual stored property, i.e. lightSaberColor that has some other behavior?

除了观察者之外,存储的属性没有行为,所以真的没有什么可以覆盖的.通过上述机制可以为属性赋予不同的值.这正是问题中的示例试图实现的目标,但使用了不同的语法.

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屋!

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