zoukankan      html  css  js  c++  java
  • 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:

  • 相关阅读:
    魔塔猎人上线后反馈和后期计划
    自己做的roguelike+恶魔城游戏《魔塔猎人》已发布。
    我的开源项目
    Unity3D工程源码目录
    小二助手(react应用框架)-http访问
    小二助手(react应用框架)-概述
    unity3d开发app的框架
    为小团队协作和个人任务管理而生的Team应用
    使用unity3d开发app
    好久未登陆
  • 原文地址:https://www.cnblogs.com/feng9exe/p/9459963.html
Copyright © 2011-2022 走看看