Swift为什么不强迫我指定的初始化程序调用super? [英] Why doesn't Swift force my designated initializer to call super?

查看:80
本文介绍了Swift为什么不强迫我指定的初始化程序调用super?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码在Swift中是合法的:

This code is legal in Swift:

class Snapper : NSObject {
    var anim : UIDynamicAnimator
    init(referenceView:UIView) {
        self.anim = UIDynamicAnimator(referenceView:referenceView)
        // super.init()
    }
}

观察到在初始化程序中我没有调用super.init();我注释掉那条线.但是Swift编译器没有抱怨.为什么?我认为有一个规则,您指定的初始化器必须调用其超类的指定初始化器.我有一个超类,即NSObject.

Observe that in my initializer I didn't call super.init(); I commented out that line. But the Swift compiler doesn't complain. Why? I thought there was a rule that your designated initializer must call a designated initializer of its superclass. And I have a superclass, namely NSObject.

这是一个错误吗?还是将NSObject作为您的超类是一种特殊情况?如果是这样,为什么?我意识到NSObject没有需要初始化的实例变量,但是我们如何知道它的init并没有做其他需要做的事情呢? Swift不应该在这里给出编译错误吗?

Is this a bug? Or is having NSObject as your superclass a special case? If so, why? I realize that NSObject has no instance variables that need initialization, but how do we know that its init doesn't do other things that need doing? Shouldn't Swift be giving a compile error here?

推荐答案

这不是答案的答案,但是在[NSObject init]上添加符号断点表明即使super.init()被注释掉,它也会被调用.

It's not an answer of the why but adding a symbolic breakpoint on [NSObject init] shows that it gets called even if super.init() is commented out.

这绝对是一种特殊情况,因为用任何其他类替换NSObject会使编译器再次警告缺少的超级调用.我的猜测是编译器将这种情况作为一种特殊情况处理,因为它是我们的基类,只有一个已知的指定初始值设定项.

It definitely seems a special case as replacing NSObject with any other class makes the compiler warn again about the missing super call. My guess is the the compiler handles this as a special case given that it's our base class with just one known designated initializer.

这篇关于Swift为什么不强迫我指定的初始化程序调用super?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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