ios – Swift 2.0中的协议扩展方法调度

ios – Swift 2.0中的协议扩展方法调度,第1张

概述我正面临协议方法调度的问题. 我有一个类层次结构,看起来像这样: protocol E { func test()}extension E { func test() { print("jello") }}class A: E {}class B: A { func test() { print("hello") 我正面临协议方法调度的问题.

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

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

但是当我在一个静态强制输入A的B类实例上调用test时,“jello”被打印出来,而不是“你好”.

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

我的理解是测试方法打印“jello”被“集成”到A的实例中(因为A符合E协议).然后我在B中提供另一个测试实现(继承形式A).我认为多态将在这里工作,并在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()

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

你们有任何解决方法吗?

解决方法 闻起来像个臭虫.

我想出的唯一解决方法是非常难看……

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中的协议扩展方法调度全部内容,希望文章能够帮你解决ios – Swift 2.0中的协议扩展方法调度所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1054302.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存