简体   繁体   English

Swift:使用指定的初始化程序覆盖便利性

[英]Swift: Overriding a convenience with a designated initializer

The Swift documentation states the following: Swift文档说明了以下内容:

If the initializer you are overriding is a convenience initializer, your override must call another designated initializer from its own subclass, as per the rules described above in Initializer Chaining. 如果要覆盖的初始化程序是一个便捷初始化程序,则根据上面在初始化程序链中描述的规则,您的覆盖必须从其自己的子类中调用另一个指定的初始化程序。

This means, that when I define an initializer with the same signature as a convenience initializer from the base class, then it must also act as a convenience initializer. 这意味着,当我使用与基类中的convenience初始化程序相同的签名定义初始化程序时,它也必须充当convenience初始化程序。 I cannot "override" a convenience initializer with a designated initializer. 我不能用designated初始化程序“覆盖” convenience初始化程序。

This seems awkward to me: There might be various cases where a signature, eg, (String) is only a convenience init for the base class but a designated init for a subclass. 这对我来说似乎很尴尬:可能存在签名的各种情况,例如(String)只是基类的便利init,而是子类的指定init。 In contrast to methods, only because two initializer have the same signature, they do not have to perform a similar task. 与方法相反,仅因为两个初始化程序具有相同的签名,它们不必执行类似的任务。 A signature of (String) could mean something completely different for a subclass. (String)签名可能意味着子类完全不同。

  1. So, why did they add this restriction? 那么,他们为什么要加上这个限制呢?
  2. How can I circumvent it? 我怎么能绕过它呢? Ie, if I do need a non-convenience initializer with the same signature as a convenience initializer in the base class, what should I do? 即,如果我确实需要一个与基类中的便利初始化程序具有相同签名的非便利初始化程序,我该怎么办? My only guess would be adding an unused dummy parameter only to distinguish between them. 我唯一的猜测是添加一个未使用的虚拟参数,仅用于区分它们。 But this seems very hacky 但这似乎非常hacky

What they mean is that if the initialiser that you have after overriding is a convenience initialiser, then you must follow Initialiser Chaining. 它们的含义是,如果覆盖的初始化程序是便捷初始化程序,则必须遵循Initialiser Chaining。

The following works fine meaning you can override a convenience initialiser with a designated initialiser : 以下工作正常意味着您可以使用指定的初始化器覆盖便利初始化器:

class Base {
    var x = 0
    init() {}
    convenience init(_: Int) {
        self.init()
        self.x = 5
    }
}

class Derived : Base {
    init() {}
    init(_: Int) {
        super.init()
        self.x = 10
    }
}

var i = Derived(1)     // x = 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM