xcode - SWIFT:init 和 super.init 之间的区别

标签 xcode swift

我正在阅读  的 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
    }
}

Source

关于xcode - SWIFT:init 和 super.init 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36916788/

相关文章:

ios - 如何直接在 swift 类文件中创建到 Table View Controller Scene 的 segue?

ios - 显示空单元格的 TableView

ios - 在同一个标​​签栏项目中实例化 View Controller 许多关系

swift - 相机 View 作为模糊背景?

xcode - 使用Cordova CLI构建和打包iOS应用程序时遇到麻烦

iOS - 缺少推送通知授权

Swift:如何通过引用分配一个可选的

Swift:线程 1:信号 SIGABRT

iphone - 在 'Music' 应用程序中在 UITableView 中创建一个部分

ios - 如何修复 UICollectionViewCell 中的图像高度?