我有以下代码:
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")
最后一行是一个编译错误:
‘ILStringProperty’ cannot be constructed because it has no accessible initializers
如果我重写init:
override init(_ value: String) {
super.init(value)
}
会工作,但我不喜欢它.为什么当我不添加/修改它时,我需要覆盖它?
我做错了吗?
更新:从尼基塔Leonov和Icaro跟进问题的答案
首先关于所有属性都必须有默认值,我觉得我满足这个规则,其中一个可选的var默认为一个零值,不是吗?即使我写var值:T? = nil没有解决它.
然后从同一个documentation部分“自动初始化程序继承”:
superclass initializers are automatically inherited if certain conditions are met
一个条件是:
If your subclass doesn’t define any designated initializers,it automatically inherits all of its superclass designated initializers.
我认为上面的代码确实满足了.如果我不会使用泛型,这实际上将会起作用:
class ILProperty {
var value: Any?
init(_ value: Any) {
self.value = value
}
}
class ILStringProperty: ILProperty {
}
let x = ILStringProperty("X")
这个规则是否也适用于泛型类?
解决方法
您的代码示例中的最后一行不再给出编译错误(自Swift 3以来).在
Swift 3 Language Changes没有提到这个,所以我只能假设这是一个bug.