swift - 在 Swift 中,为什么子类方法不能覆盖父类(super class)中协议(protocol)扩展提供的方法

标签 swift protocols swift2 xcode7

我知道这个问题的标题令人困惑,但下面的示例解释了奇怪的行为:

protocol Protocol {
    func method() -> String
}

extension Protocol {
    func method() -> String {
        return "From Base"
    }
}

class SuperClass: Protocol {
}

class SubClass: SuperClass {
    func method() -> String {
        return "From Class2"
    }
}

let c1: Protocol = SuperClass()
c1.method() // "From Base"
let c2: Protocol = SubClass()
c2.method() // "From Base"

为什么 c1.method()c2.method() 返回相同的值? SubClass 中的method() 怎么不起作用?

有趣的是,无需声明 c2 的类型,这将起作用:

let c2  = SubClass()
c2.method() // "From Class2"

最佳答案

问题是 c1c2 属于 Protocol 类型,因为您已经以这种方式明确定义了它们的类型(记住:协议(protocol)是完全成熟的类型)。这意味着,当调用 method() 时,Swift 会调用 Protocol.method


如果你定义如下:

let c3 = SuperClass()

...c3SuperClass 类型。由于 SuperClass 没有更具体的 method() 声明,当调用 c3.method( )


如果你定义如下:

let c4 = SubClass()

...c4SubClass 类型。由于 SubClass 确实有一个更具体的 method() 声明,因此在调用 c4.method( )


您还可以让 c2 调用 SubClass.method(),方法是将其向下转换为 `SubClass:

(c2 as! SubClass).method() // returns "From Class2"

这是关于 SwiftStub 的演示.

关于swift - 在 Swift 中,为什么子类方法不能覆盖父类(super class)中协议(protocol)扩展提供的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32994448/

相关文章:

ios - 获取调整后的标签字体大小

ios - 当类符合包含变异功能的协议(protocol)时会发生什么?

3秒后Swift 2执行功能

swift - 订阅 NSError 的 userInfo

IOS:从不同 View 的类更改 View 的正确方法是什么?

ios - 根据 View 设置按钮一侧的角半径?

ios - 如何在 iOS 上更改 UIButton 的文本颜色并使其保持选中状态

swift 3 FFT 获取声音频率 m4a

swift - Swift 中基于协议(protocol)的通用树结构

android - Android 上的 Youtube - 如何检查它使用的协议(protocol)?