【发布时间】:2018-03-12 15:59:10
【问题描述】:
我正在关注本教程:https://www.raywenderlich.com/160728/object-oriented-programming-swift
...并尝试对代码进行一些个人调整,看看我是否能够自己理解一些核心概念。
我最终得到以下代码:
class Instrument {
var brand: String
var model: String
init(brand: String, model: String) {
self.brand = brand
self.model = model
}
func tune() {
print("\(model) tuned !")
}
func play() {
print("\(model) plays an improvised melody")
}
func perform() {
print(tune())
print(play())
}
}
还有这个子类:
class Piano: Instrument {
var hasPedals: Bool
init(hasPedals: Bool ) {
self.hasPedals = hasPedals
super.init(brand: brand, model: model)
}
}
此时,我收到以下错误消息:
游乐场执行失败:
错误:面向对象编程.playground:28:41:错误:使用 在 super.init 初始化 self 之前,属性访问“模型”中的“自我” super.init(品牌:品牌,型号:型号) ^
错误:面向对象编程.playground:28:27:错误:使用 在 super.init 初始化自我之前,属性访问“品牌”中的“自我” super.init(品牌:品牌,型号:型号)
我觉得这是一个非常明显的错误,但我不知道如何解决它。
编辑:非常感谢你们提供的超级干净的答案。现在对我来说很有意义!
如果我理解正确,即使您在子类中使用自定义 init 方法,您也需要初始化所有存储的属性(来自超类和子类)对吗?
【问题讨论】:
标签: swift