According to Apple's documentation Swift does not necessary require override of initializer. In a following code example Bar
inherits initializer of Foo
:
class Foo {
let value: Int
init(value: Int = 5) {
self.value = value
}
}
class Bar: Foo {
}
As soon as we add some generic into Foo
such as class Foo<T> {
Xcode provides us a error Initializer does not override a designated initializer from its superclass
. Is there a documentation or swift evolution discussion that explains why it is happening?
Update. It seems that generic is not a major cause for override requirement. Here are an option how to define a class with generic that does not require override of designated initializer:
protocol FooProtocol {
associatedtype T
}
class Foo<U>: FooProtocol {
typealias T = U
let value: Int
init(value: Int, otherValue: T) {
self.value = value
self.otherValue = otherValue
}
}
class Bar: Foo<Int> {
}
However there is another interesting observation of behavior. Defining initializer like following cause override requirement:
init(value: Int = 5) {
self.value = value
}
The funny thing thing that adding one more parameter as following into such designated initializer cause this override requirement to disappear:
init(value: Int = 5, otherValue: T) {
self.value = value
}
Update 2. I can not find a logical explanation to this behavior, at this point I reported it as Compiler bug — https://bugs.swift.org/browse/SR-1375
I actually filled a bug report for inheriting from generic class:
It was back in November last year and didn't get an answer yet, so ¯_(ツ)_/¯
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With