加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift protocol 与类继承结合时的bug

发布时间:2020-12-14 05:12:02 所属栏目:百科 来源:网络整理
导读:? protocol CommonTrait: class { ? ? func commonBehavior() - String } ? extension CommonTrait { ? ? func commonBehavior() - String { ? ? ? ? return "from protocol extension" ? ? } } ? class CommonThing { ? ? func say() - String { ? ? ? ? re

?

protocol CommonTrait: class {

? ? func commonBehavior() -> String

}

?

extension CommonTrait {

? ? func commonBehavior() -> String {

? ? ? ? return "from protocol extension"

? ? }

}

?

class CommonThing {

? ? func say() -> String {

? ? ? ? return "override this"

? ? }

}

?

class ParentClass: CommonThing,CommonTrait {

? ? override func say() -> String {

? ? ? ? return commonBehavior()

? ? }

}

?

class AnotherParentClass: CommonThing,CommonTrait {

? ? override func say() -> String {

? ? ? ? return commonBehavior()

? ? }

}

?

class ChildClass: ParentClass {

? ? override func say() -> String {

? ? ? ? return super.say()

? ? ? ? // it works if it calls `commonBehavior` here and not call `super.say()`,but I don‘t want to do that as there are things in the base class I don‘t want to have to duplicate here.

? ? }

? ? func commonBehavior() -> String {

? ? ? ? return "from child class"

? ? }

}

?

let child = ChildClass()

child.say() // want to see "from child class" but it‘s "from protocol extension”

?

实现链条缺失时会使用protocol的缺省实现。不能路由到真正的实现。

?

https://stackoverflow.com/questions/31795158/swift-2-protocol-extension-not-calling-overridden-method-correctly

?

?

Unfortunately protocols don‘t have such an dynamic behavior (yet).

But you can do that (with the help of classes) by implementing?commonBehavior()?in the?ParentClass?and overriding it in the?ChildClass. You also need?CommonThing?or another class to conform to?CommonTrait?which is then the superclass of?ParentClass:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读