ios - Swift 2.0 中的协议(protocol)扩展方法分派(dispatch)

标签 ios xcode swift polymorphism xcode7

我遇到了有关协议(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/

相关文章:

iphone - 具有多个实体的 CoreData 编程

objective-c - 在 Objective-C 中保存空白文件

Swift UIWebView 约束全屏

ios - 在 Core Data 中,如何在 swift 4 中执行 `if exists update else insert`?

iphone - 如何使带有 UIPageViewController 点的底部栏半透明?

ios - 以立体声 iOS 录制音频

ios - View 的内容在关闭后消失

ios - SFSafariViewController 在导航栏和底部工具栏中是否始终具有相同的 UI 元素?

ios - UITableView - 如何在拖放期间更改单元格的背景颜色?

ios - 滑动删除功能插入包含Core Data