我遇到了有关协议(protocol)方法分派(dispatch)的问题。
我有一个看起来像这样的类层次结构:
protocol E {
func test()
}
extension E {
func test() {
print("jello")
}
}
class A: E {
}
class B: A {
func test() {
print("hello")
}
}
但是当我调用类 B
的实例上的 test
静态强制键入 A
时,打印的是“jello”,而不是“你好”。
let b: A = B() // prints "jello" not "hello"
b.test()
我的理解是 test
打印“jello”的方法被“集成”到 A
的实例中(因为 A
符合 E
协议(protocol))。然后,我在 B
中提供了另一个 test
的实现(它继承了 A
的形式)。我认为多态性可以在这里工作,并且在 A
引用中存储的 B
实例上调用 test
将打印 hello
。这里发生了什么?
它在不使用任何协议(protocol)时完美运行:
class A {
func test() {
print("jello")
}
}
class B: A {
override func test() {
print("hello")
}
}
let b: A = B() // prints "hello"
b.test()
采用向父类添加新方法并在子类中提供新实现的协议(protocol)与直接在父类中编写此方法然后在子类中覆盖它有什么不同?
你们有什么解决办法吗?
最佳答案
闻起来像 bug 。
我想出的唯一解决方法非常丑陋...
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()
关于ios - Swift 2.0 中的协议(protocol)扩展方法分派(dispatch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32734403/