Swift继承函数返回类型不能是子类型

标签 swift inheritance swiftui subclass return-type

考虑以下代码:

class A {}
class B: A {}
protocol P {
    var a: A {get}
}
class P1: P {
    let a: A = B() // No problem
}
class P2: P {
    let a: B = B() // Can't compile!!
}

既然BA的子类,为什么我们不能将B作为var a<的返回类型

最佳答案

您不能这样做,因为 P 协议(protocol)明确要求符合规范的类具有 A 类型的属性。

您始终可以在协议(protocol)中使用关联类型和泛型:

class A {}
class B: A {}
protocol P {
    associatedtype T: A
    var a: T { get }
}
class P1: P {
    let a: A = B()
}
class P2: P {
    let a: B = B()
}

但请记住,如果您这样做,则不能直接使用 P 协议(protocol)作为类型,而只能与泛型一起使用:

enter image description here

关于Swift继承函数返回类型不能是子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64782592/

相关文章:

ios - MapKit视角

swift - 使用索引访问元组(由 libc 定义)

c++ - 基类中的 switch 语句需要使用派生类的值

c++ - 基于集合派生对象中存在的类型选择行为的模式

swift - 拖动手势时将矩形限制到屏幕边缘

swiftui - 在初始化所有存储的属性之前使用“self”错误 SwiftUI

SwiftUI:在编辑开始时清除 TextField

ios - 在 View Controller /页面 View Controller 中全屏显示图像(快速)

ios - 从一个 ViewController 到另一个 ViewController 保存和删除 NSUserDefaults - Swift 2

html - html中可能有 "inheritance"吗?