• swift protocol 与类继承结合时的bug


    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:

  • 相关阅读:
    linux清理缓存
    HTMl5的sessionStorage和localStorage
    jQueryValidation插件API 学习
    notepad++去空格空行技巧
    关于前端的一些疑问
    ios上传图片遇见了一个TimeoutError(DOM Exception 23)异常
    js不执行的问题
    input type=file 怎么样调取用户手机照相机
    在调用方法给安卓传参遇到的问题
    canvas压缩图片成base64,传到后台解码需要注意的问题
  • 原文地址:https://www.cnblogs.com/feng9exe/p/9459963.html
Copyright © 2020-2023  润新知