Swift:覆盖也是父类子类的子类属性 Class 属性 Class

Swift: Override Subclass Properties that are also Subclasses of the Parent Class Property Class

看似是一个令人困惑的问题,但其实很简单。我想做这样的事情,但 Swift 不允许:

class A {}
class B : A {}
class C {
    var prop: A?
}
class D : C {
    override var prop : B?
}

取自here:

Overriding Property Getters and Setters

You can provide a custom getter (and setter, if appropriate) to override any inherited property, regardless of whether the inherited property is implemented as a stored or computed property at source. The stored or computed nature of an inherited property is not known by a subclass—it only knows that the inherited property has a certain name and type. You must always state both the name and the type of the property you are overriding, to enable the compiler to check that your override matches a superclass property with the same name and type.

看来你做不到。

没有明智的方法来完成您的要求,即 covariance/contravariance。想象一下这段代码:

func storeProperty(_ c: C) {
  c.prop = A()
}

let d = D()
storeProperty(d)
let b: B = d.prop

如果您的想法可行,我们会遇到类型错误 — B 类型的变量在运行时不包含 B!