swift子类*总是*必须调用super.init() [英] Does a swift subclass *always* have to call super.init()
问题描述
如果我有一个swift子类:
If I have a swift subclass that:
- 不需要访问
self
- 无需访问
self
- doesn't need to access
self
- doesn't need to access any properties on
self
$上的任何属性b
$ b
我是否仍然需要在子类的 init()$ c中调用
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()
ina
将被调用
override init()
inb
will be called- then the
init()
ina
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屋!