Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift generic superclass' init not accessible when constructing its subclass

Tags:

ios

swift

I have the following codes:

class ILProperty<T> {
    var value: T?
    init(_ value: T) {
        self.value = value
    }
}

typealias ILStringProperty = ilStringProperty<String>
class ilStringProperty<String>: ILProperty<String> {
}

let x = ILStringProperty("X")

The last line is a compile error:

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

If I override the init:

override init(_ value: String) {
    super.init(value)
}

will work but I don't like it. Why do I need to override it when I won't add/modify it?

Am I doing something wrong?

Update: Follow up questions to answers from Nikita Leonov and Icaro

First regarding all properties must have default value, I do think I satisfied this rule where an optional var is defaulted with a nil value, isn't it? Though even if I write var value: T? = nil doesn't solve it.

Then from the same documentation section "Automatic Initializer Inheritance":

superclass initializers are automatically inherited if certain conditions are met

One condition is:

If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.

Where I do think the code above does met. This actually will work if I will not use generics:

class ILProperty {
    var value: Any?
    init(_ value: Any) {
        self.value = value
    }
}
class ILStringProperty: ILProperty {
}
let x = ILStringProperty("X")

Should this rule also apply to generic classes?

like image 845
jolen Avatar asked Jun 25 '15 02:06

jolen


Video Answer


1 Answers

The last line in your code sample no longer gives a compile error, (since Swift 3). There is no mention of this in the Swift 3 Language Changes, so I can only assume that this was a bug.

like image 180
ganzogo Avatar answered Oct 20 '22 00:10

ganzogo