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

为什么我们在Swift中覆盖初始值设定项?

发布时间:2020-12-14 04:31:37 所属栏目:百科 来源:网络整理
导读:从 Swift’s documentation开始: Unlike subclasses in Objective-C,Swift subclasses do not inherit their superclass initializers by default. 但随后它说: When you write a subclass initializer that matches a superclass designated initializer,
从 Swift’s documentation开始:

Unlike subclasses in Objective-C,Swift subclasses do not inherit
their superclass initializers by default.

但随后它说:

When you write a subclass initializer that matches a superclass
designated initializer,you are effectively providing an override of
that designated initializer. Therefore,you must write the override
modifier before the subclass’s initializer definition.

来自Java背景,其中构造函数不是继承的,我不明白它是如何工作的.为什么我们要覆盖默认情况下不继承的初始化程序?在我看来,像构造函数一样,初始化程序将隐式命名为类本身,并且可以在子类中重载(例如,Java中的类Dog只有名为Dog的构造函数).但我不明白这个覆盖父初始化器的想法.

解决方法

子类可能不会“默认”继承其超类初始值设定项,但它们可以继承(例如,如果您不提供任何指定的初始值设定项,您将自动继承超类的所有指定初始值设定项…请参阅 Automatic Initializer Inheritance).

考虑一个名为Chihuahua的Dog子类:如果你没有在Chihuahua中实现任何指定的初始值设定项,你自动继承Dog初始值设定项,而不需要额外的代码.但是如果您确实需要因某种原因覆盖它,那么只需要从Chihuahua指定的初始化程序中调用Dog指定的初始化程序.如果您的Chihuahua初始化程序与Dog指定的初始化程序具有相同的签名,则必须显式提供override关键字.

(编辑:李大同)

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

    推荐文章
      热点阅读