ganzogo ganzogo - 21 days ago 7
Swift Question

Inheriting initializer from generic class

I've seen some discussions about this problem, but have not read a satisfactory explanation. Can anybody tell me why this does not work?

class Parent<T> {

var data:T

init(data:T) {
self.data = data
}
}

class Child : Parent<Int> {}

let c = Child(data: 4)


The last line gives the error:

'Child' cannot be constructed because it has no accessible initializers


Do I really need to implement the initializer just to call
super
?

Edit:

To give a bit of context, the real code looks closer to the below. I have an
Action
class which uses generics, because I have another bit of code which can chain actions together and I want to use Swift's type safety to ensure that actions can be chained. Then I have a bunch of subclasses classes (e.g.
CustomAction
). I am looking for a way to avoid overriding the
init
method in each of the subclasses. Or alternatively, I want to understand why that's not possible.

class Action<Input, Output> {

var cachedOutput:Output?

init(cachedOutput:Output?) {
self.cachedOutput = cachedOutput
}
}

protocol CustomInput {}
protocol CustomOutput {}

class CustomAction : Action<CustomInput, CustomOutput> {
}

Answer

This now works in Swift 3. My original example now compiles. There is no mention of this in the Swift 3 Language changes, so I can only assume that this was a bug.