我正在阅读Sw的The
Swift Programming Language一书.
书中说Init是一个初始化器,用于在创建实例时设置类. (我的理解是:通过创建实例,将执行init()中的代码块).
然而,这本书显示了super.init,但没有说明任何事情.
解决方法
官方文档确实涵盖了初始化超类的方面:
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.
对应的示例代码:
超类:
class Vehicle { var numberOfWheels = 0 var description: String { return "\(numberOfWheels) wheel(s)" } }
子类:
class Bicycle: Vehicle { override init() { super.init() numberOfWheels = 2 } }