协议扩展方法在Swift 2.0中调度

我正在面对有关协议方法调度的问题。

我有一个类层次结构,看起来像这样:

protocol E { func test() } extension E { func test() { print("jello") } } class A: E { } class B: A { func test() { print("hello") } } 

但是当我静态地强制typesA B类实例调用test时,“jello”被打印,而不是“hello”。

 let b: A = B() // prints "jello" not "hello" b.test() 

我的理解是打印“jello”的test方法被“集成”到A实例中(因为A符合E协议)。 然后我在B里面提供另一个test实现(inheritanceAforms)。 我认为多态性将在这里工作,并调用test存储在里面的B实例引用将打印hello 。 这里发生了什么事?

当不使用任何协议时,它是完美的工作:

 class A { func test() { print("jello") } } class B: A { override func test() { print("hello") } } let b: A = B() // prints "hello" b.test() 

与在父类中添加新方法并在子类中提供新实现的协议有所不同,而不是直接在父类中编写此方法,然后在子类中重写该方法?

你们有没有解决办法?

闻起来像一个错误。

我想出的唯一解决方法是非常丑陋的…

 protocol E { func test() } func E_test(_s: E) { print("jello") } extension E { func test() { E_test(self) } } class A: E { func test() { E_test(self) } } class B: A { override func test() { print("hello") } } let b: A = B() b.test() 

这确实是一个错误。 这里是它的链接: https : //bugs.swift.org/browse/SR-103

Interesting Posts