在Swift中,为什么子类方法不能覆盖超类中协议扩展提供的方法

aqu*_*ach 6 protocols swift xcode7 swift2

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

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"
Run Code Online (Sandbox Code Playgroud)

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

有趣的是,在没有声明c2的类型的情况下,这将起作用:

let c2  = SubClass()
c2.method() // "From Class2"
Run Code Online (Sandbox Code Playgroud)

Jer*_*myP 0

我不太确定底层机制,但它一定与协议不一定允许继承这一事实有关。

解决此问题的一种方法是将方法添加到SuperClass

import Foundation
protocol Protocol: class {
    func method() -> String
}

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

class SuperClass: Protocol {
    func method() -> String {
        return "From Super"
        }
}

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

let c1: Protocol = SuperClass()
c1.method() // "From Super"
let c2: Protocol = SubClass()
c2.method() // "From Class2"
Run Code Online (Sandbox Code Playgroud)