If I declare
public class A: NSObject {
public class X { }
public init?(x: X? = nil) { }
}
all is fine. When using it like let a = A()
, the initializer is called as expected.
Now, I'd like to have the nested class X
private, and the parameterized init
as well (has to be, of course). But a simple init?()
should stay publicly available as it was before. So I write
public class B: NSObject {
private class X { }
private init?(x: X?) { }
public convenience override init?() { self.init(x: nil) }
}
But this gives an error with the init?()
initializer: failable initializer 'init()' cannot override a non-failable initializer with the overridden initializer being the public init()
in NSObject
.
How comes I can effectively declare an initializer A.init?()
without the conflict but not B.init?()
?
Bonus question: Why am I not allowed to override a non-failable initializer with a failable one? The opposite is legal: I can override a failable initializer with a non-failable, which requires using a forced super.init()!
and thus introduces the risk of a runtime error. To me, letting the subclass have the failable initializer feels more sensible since an extension of functionality introduces more chance of failure. But maybe I am missing something here – explanation greatly appreciated.