Bug? "use of unimplemented initializer"

Hi,


I tried to create a subclass of UIStackView, but I get a strange error related to `init`. My views are created in code, not in IB, so I wrote a basic `init()` that calls up to the designated initalizer. Like this:


class MyView : UIStackView {
   [ Some `let` instance variables ]
   init() {
       [ set the instance vars ]
       let arranged = ...
       super.init(arrangedSubviews: arranged)  // the designated initializer
       ...
    }
   required init?(coder aDecoder: NSCoder) { fatalError("not impl") } // xcode requires this one
}


At runtime I get this error:


fatal error: use of unimplemented initializer 'init(frame:)' for class 'MyProject.MyView'.

Stack:

MyView.init(frame:)

UIStackView.init(arrangedSubviews:)

MyView.init()


That looks to me like something is wrong with the library or the language. Am I right? Or missing something?


Rob

That looks to me like something is wrong with the library or the language.

Seems to be related to both, and better send a Bug Report.


The language Objective-C does not have much strict rules of initializing, and the library almost of all Apple's frameworks are written in Objective-C.

So, - initWithArrangedSubviews: may (very likely) calling [self initWithFrame:] rather than [super initWithFrame:], in such cases this sort of runtime error may happen.


As you may already know, inheriting init(frame:) would resolve your case:

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

In some cases, it is very hard to subclass such classes in Swift.

Okay, am I correct that overriding init(frame:) and calling super like that goes against the Swift docs, which say you should call the designated initializer of the superclass, which is init(arrangedSubviews:). That makes me worry that they'll fix the bug and break my code. So, I think I'll just subclassed UIView and put a stack inside it. An extra view in the hierarchy, but less scary.


Rob

am I correct that overriding init(frame:) and calling super like that goes against the Swift docs

Not very correct. From the Swift side of view, inherited init(frame:) of UIStackView is treated as another designated initializer. (Remember Swift classes can have multiple designated initializers.)


I think I'll just subclassed UIView and put a stack inside it.

Your choice is reasonalbe enough, as the behaviour of Swift's importing inconsistent Objective-C classes such as above is not well documented and may change in the future. Though I'm not sure which way I would do...

Bug? "use of unimplemented initializer"
 
 
Q