为什么不允许子类使用派生类型覆盖超类属性?

Why disallow subclasses to override superclass properties with a derived type?

Swift 编程语言允许子类覆盖具有相同类型 T 的超类属性,但不能覆盖具有不同类型 S 的超类属性,即使 S 派生自 T 也不行。这是来自 https://docs.swift.org/swift-book/LanguageGuide/Inheritance.html 的引述:

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.

重写方法时,Swift 确实允许重写子类方法 return 派生自超类方法 return 类型的类型。

我的问题是:不允许子类覆盖具有派生自 T 的类型 S 的超类属性的动机是什么?

这个其实不限于Swift。这会破坏多态性。请参阅 wikipedia: Subtyping

上的子类型规则

基本上,请考虑以下示例:

class A {
   var x: NSObject?
}

class B: A {
   override var x: NSNumber?
}

并考虑:

let b = B(x: 1)
let a: A = b // it's a subclass, polymorphism allows to assign it to A
a.x = NSObject() // let's assign NSObject() because A.x takes NSObject
print(b.x) // b.x should be a NSNumber now but we have assigned a NSObject?

你必须意识到 属性 是两个函数的组合,setter 和 getter。您可以将更具体的类型(协变类型)添加到 getter(函数的 return 值),但您不能为 setter 执行此操作(覆盖函数的参数需要逆变) .

这也告诉你这将适用于只读 属性:

class A {
    var x: NSObject? {
        return NSObject()
    }
}

class B: A {
    override var x: NSNumber? {
        return NSNumber()
    }
}