swift子类*总是*必须调用super.init() [英] Does a swift subclass *always* have to call super.init()

查看:394
本文介绍了swift子类*总是*必须调用super.init()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个swift子类:

If I have a swift subclass that:


  1. 不需要访问 self

  2. 无需访问 self

  1. doesn't need to access self
  2. doesn't need to access any properties on self

$上的任何属性b
$ b

我是否仍然需要在子类的 init() super.init() $ c>方法?

Do I still have to call super.init() in the subclass's init() method?

*注意:这是一个问题与答案不同的问题这里是SO ,因为上面的1和2中列出了具体内容。

*Note: This is a different question than the one asked and answered here on SO because of the specifics listed in 1 and 2 above.

推荐答案

不,你没必要。

假设您有以下内容class。

Assume you have the following classes.

class a {
    let name: String

    init() {
        name = "james"
    }
}

class b: a {
    let title: String

    override init() {
        title = "supervisor"
    }
}

如果使用

实例化变量,请让myVar = b()

然后,


  • 覆盖 b 中的init()将被调用

  • 然后 init() in a 将被调用

  • override init() in b will be called
  • then the init() in a will be called

即使你没有明确地调用 super.init()

Even though you didn't explicitly call super.init().

Chris Laettner已经在快速用户的电子邮件列表中证实了这一点。
当你的超类有一个带有零参数init的指定初始值时,它会启动。这就是为什么你不必在从NSObject派生时调用super.init()。

This has been confirmed by Chris Laettner on the swift-user's email list. It kicks in when your super class has a single designated initializer with a zero-argument init. This is why you don’t have to call super.init() when deriving from NSObject.

*感谢Wingzero在下面的评论

*Thanks to Wingzero's comment below

这篇关于swift子类*总是*必须调用super.init()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆