我正在阅读 的 The Swift Programming Language 一书。
书上说 Init 是一个初始化程序,用于在创建实例时设置类。 (我的理解是:通过创建实例,将执行 init() 中的代码块)。
然而,这本书显示了 super.init 但没有说明任何相关信息。
最佳答案
官方文档确实涵盖了初始化父类(super class)的方面:
The init() initializer for Bicycle starts by calling super.init(), which calls the default initializer for the Bicycle class’s superclass, Vehicle. This ensures that the numberOfWheels inherited property is initialized by Vehicle before Bicycle has the opportunity to modify the property. After calling super.init(), the original value of numberOfWheels is replaced with a new value of 2.
对应的示例代码:
父类(super class):
class Vehicle {
var numberOfWheels = 0
var description: String {
return "\(numberOfWheels) wheel(s)"
}
}
子类:
class Bicycle: Vehicle {
override init() {
super.init()
numberOfWheels = 2
}
}
关于xcode - SWIFT:init 和 super.init 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36916788/