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?
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.
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