ios - Swift 和来自父类(super class)的属性继承

标签 ios swift inheritance swift2

我有A类类(class)。及其子类 B。我需要重写其属性的类型。更改协议(protocol)也可以。我怎样才能做到这一点?

class A {
 var property: String (or SomeProtocolA)
}

class B: A {
 var property: Int (or SomeProtocolB)
}

也许可以为子类中的属性添加第二个协议(protocol)的支持?

最佳答案

你不能,这表明设计很糟糕。

假设 A 类有一个函数:

class A {
    var property: String (or SomeProtocolA)

    func getMyString() -> String {
        return property
    }
}

现在类 B 继承了它,同时“覆盖”属性:

class B : A {
    var property: Int(or SomeProtocolB)

    // func getMyString() -> String { //inherited from superclass
    //    return property //type error, expected String, returning Int
    //}
}

关于ios - Swift 和来自父类(super class)的属性继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37868025/

相关文章:

ios - 初始化 SKView 时出现奇怪的错误

ios - Xcode clang : error: unable to execute command: Segmentation fault: 11

ios - 从 block 返回导航

ios - SWIFT:如何向 NSDate 对象添加小时数

ios - 我在 appDelegate 中收到错误?

c++ - 如何检查派生类的类型? (C++ Instanceof)

postgresql - Postgres : Performance and correctness of inheritance-foreign-key workaround

ios - 在 CALayer 层次结构中组合多个 CAAnimation

ios - 尝试绘制图表时应用程序崩溃

c++ - C++ 中的多态问题