Why doesn't Swift force my designated initializer to call super?

ぐ巨炮叔叔 提交于 2019-12-19 10:13:43

问题


This code is legal in Swift:

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

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.

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?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/30820816/why-doesnt-swift-force-my-designated-initializer-to-call-super

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!