I'm writing code in Swift, and using https://github.com/evermeer/EVReflection. However, Xcode is playing shenanigans with my class structure - in a few places, it claims I need to include a required initialized, declared in EVObject
, but not in other places. Consider the following example:
class Root: EVObject {
}
class MidA: Root {
required init() {
}
init(blah: String) {
}
}
class LeafA: MidA {
required init() {
super.init()
}
} // Error: 'required' initializer 'init(coder:)' must be provided by subclass of 'EVObject'
class MidB: Root {
required init() {
}
}
class LeafB: MidB {
required init() {
super.init()
}
} // No error
EVObject
contains the following method definition:
public convenience required init?(coder: NSCoder) {
self.init()
EVReflection.decodeObjectWithCoder(self, aDecoder: coder, conversionOptions: .DefaultNSCoding)
}
Describing the example in words, there's a root object, Root
, which extends EVObject
, and it forks into two subclasses, MidA
and MidB
, which each have a subclass of their own: LeafA
and LeafB
. LeafA
and LeafB
are identical aside from their name and superclass. MidA
and MidB
differ only in name and in that MidA
has an additional initializer that takes a parameter.
What bearing could that possibly have on LeafA
? Having an extra initializer with a parameter seems entirely unrelated to the particular initializer declared in EVObject
(which is apparently required
, but it's not usually enforced??). Why would adding an unrelated initialized in a branch class suddenly require me, in my leaf classes, to figure out what the heck is this required
initializer I've never seen before?
It's indeed caused by the extra init
init(blah: String) {
}
That one could also be changed to:
convenience init(blah: String) {
self.init()
}
Then it won't complain about adding the required initializer.
With the convenience you specify that you will call a required initializer from there. Without that the compiler can't be sure that you do.
See also https://docs.swift.org/swift-book/LanguageGuide/Initialization.html