Swift 2.0 中的协议扩展方法调度
Protocol extension method dispatch in Swift 2.0
我遇到了有关协议方法分派的问题。
我有一个 class 层次结构,如下所示:
protocol E {
func test()
}
extension E {
func test() {
print("jello")
}
}
class A: E {
}
class B: A {
func test() {
print("hello")
}
}
但是当我在 class B
的实例上调用 test
静态强制键入 A
时,"jello" 被打印,而不是 "hello".
let b: A = B() // prints "jello" not "hello"
b.test()
我的理解是 test
方法打印 "jello" 得到 "integrated" 到 A
的实例中(因为 A
符合 E
协议).然后,我在 B
中提供 test
的另一个实现(它继承了 A
的形式)。我认为多态性在这里可以工作,并且在存储在 A
引用中的 B
实例上调用 test
将打印 hello
。这里发生了什么?
它在不使用任何协议的情况下完美运行:
class A {
func test() {
print("jello")
}
}
class B: A {
override func test() {
print("hello")
}
}
let b: A = B() // prints "hello"
b.test()
采用向我的父 class 添加新方法并在子 class 中提供新实现的协议与直接在父 [=46= 中编写此方法有何不同] 然后在 subclass?
中覆盖它
你们有什么解决方法吗?
闻起来像虫子。
我想出的唯一解决方法非常丑陋...
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()
确实是个bug。这是它的 link:https://bugs.swift.org/browse/SR-103
我遇到了有关协议方法分派的问题。
我有一个 class 层次结构,如下所示:
protocol E {
func test()
}
extension E {
func test() {
print("jello")
}
}
class A: E {
}
class B: A {
func test() {
print("hello")
}
}
但是当我在 class B
的实例上调用 test
静态强制键入 A
时,"jello" 被打印,而不是 "hello".
let b: A = B() // prints "jello" not "hello"
b.test()
我的理解是 test
方法打印 "jello" 得到 "integrated" 到 A
的实例中(因为 A
符合 E
协议).然后,我在 B
中提供 test
的另一个实现(它继承了 A
的形式)。我认为多态性在这里可以工作,并且在存储在 A
引用中的 B
实例上调用 test
将打印 hello
。这里发生了什么?
它在不使用任何协议的情况下完美运行:
class A {
func test() {
print("jello")
}
}
class B: A {
override func test() {
print("hello")
}
}
let b: A = B() // prints "hello"
b.test()
采用向我的父 class 添加新方法并在子 class 中提供新实现的协议与直接在父 [=46= 中编写此方法有何不同] 然后在 subclass?
中覆盖它你们有什么解决方法吗?
闻起来像虫子。
我想出的唯一解决方法非常丑陋...
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()
确实是个bug。这是它的 link:https://bugs.swift.org/browse/SR-103