Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了swift protocol 与类继承结合时的bug大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

  protocol CommonTrait: class {     func commonBehavior() -> String }   extension CommonTrait {     func commonBehavior() -> String {         return "from protocol extension"     } }   class CommonThi

 

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 implemenTincommonBehavior() 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:

大佬总结

以上是大佬教程为你收集整理的swift protocol 与类继承结合时的bug全部内容,希望文章能够帮你解决swift protocol 与类继承结合时的bug所遇到的程序开发问题。

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。