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

410 views Asked by At

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

There are 1 answers

7
Tomas Camin On BEST ANSWER

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.