我试图通过学习不同的教程来学习 Swift,但我遇到了一个问题。我有以下代码:
Class Vehicle {
var seats = 5
var maxSpeed = 100
}
class Bike : Vehicle{
override var seats = 3
}
但我不断收到有关尝试覆盖 var seats
的错误,指出 无法使用存储的属性“seats”覆盖
。
我做错了什么?我以为我可以覆盖继承的变量?
最佳答案
您实际上不需要覆盖该属性,只需使用不同的值进行初始化即可,这可以在初始化程序中完成:
class Vehicle {
var seats = 5
var maxSpeed = 100
}
class Bike : Vehicle{
override init() {
super.init()
self.seats = 3
}
}
至于覆盖属性,lang reference指出:
You can override an inherited instance or class property to provide your own custom getter and setter for that property, or to add property observers to enable the overriding property to observe when the underlying property value changes.
关于ios - 在 Swift 中覆盖一个 var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27972777/