加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 17:14:52 所属栏目:百科 来源:网络整理
导读:我正在阅读Sw的The Swift Programming Language一书. 书中说Init是一个初始化器,用于在创建实例时设置类. (我的理解是:通过创建实例,将执行init()中的代码块). 然而,这本书显示了super.init,但没有说明任何事情. 解决方法 官方文档确实涵盖了初始化超类的方
我正在阅读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
    }
}

Source

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读