Why doesn't Swift force my designated initiali

2020-03-25 18:37发布

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条回答
小情绪 Triste *
2楼-- · 2020-03-25 19:08

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.

查看更多
登录 后发表回答