Nic*_* B. 6 polymorphism xcode ios swift xcode7
我正面临协议方法调度的问题.
我有一个类层次结构,看起来像这样:
protocol E {
func test()
}
extension E {
func test() {
print("jello")
}
}
class A: E {
}
class B: A {
func test() {
print("hello")
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我打电话给静态强制输入test类的实例时,"jello"被打印出来,而不是"你好".BA
let b: A = B() // prints "jello" not "hello"
b.test()
Run Code Online (Sandbox Code Playgroud)
我的理解是test方法打印"jello"被"集成"到A(因为A符合E协议)的实例中.然后我提供另一个test内部实现B(继承表单A).我以为多态性会在这里工作,并呼吁test在B实例存储内A引用将打印hello.这里发生了什么事?
不使用任何协议时,它完美地工作:
class A {
func test() {
print("jello")
}
}
class B: A {
override func test() {
print("hello")
}
}
let b: A = B() // prints "hello"
b.test()
Run Code Online (Sandbox Code Playgroud)
与在父类中添加新方法并在子类中提供新实现的协议有什么不同,而不是直接在父类中编写此方法然后在子类中重写它?
你们有任何解决方法吗?
闻起来像虫子。
我想出的唯一解决方法非常丑陋......
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
274 次 |
| 最近记录: |