【问题标题】:Use of 'self' in property access 'model' before super.init initializes self super.init(brand: brand, model: model)在 super.init 初始化 self super.init(品牌:品牌,模型:模型)之前,在属性访问“模型”中使用“自我”
【发布时间】: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


    【解决方案1】:

    您正在调用超类init 方法来初始化您的子类的一部分。但是,在初始化它之前,您传递了一个未初始化的变量。只需将这些变量添加到Piano 的参数中:

    init(hasPedals: Bool, brand: String, model: String)
    

    【讨论】:

      【解决方案2】:

      仔细看:

      init(hasPedals: Bool ) {
      
          self.hasPedals = hasPedals
          super.init(brand: brand, model: model)
      
      }
      

      您传递给超级初始化程序的brandmodel 是什么?它们在哪里定义?如果您的意思是 self.brandself.model,不,您不能使用它们。它们还没有被初始化!

      在不知道您真正希望 Piano 的初始化程序是什么样的情况下,我无法准确回答问题,但解决此问题的一种方法是添加 brandmodel 参数:

      init(hasPedals: Bool, brand: String, model: String) {
      
          self.hasPedals = hasPedals
          super.init(brand: brand, model: model)
      
      }
      

      现在brandmodel 引用参数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-05
        • 2020-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多