Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Swift requires override of designated initializer of generic superclass?

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

like image 484
Nikita Leonov Avatar asked Apr 30 '16 17:04

Nikita Leonov


1 Answers

I actually filled a bug report for inheriting from generic class:

enter image description here

It was back in November last year and didn't get an answer yet, so ¯_(ツ)_/¯

like image 104
sunshinejr Avatar answered Sep 30 '22 15:09

sunshinejr