栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Swift 2协议扩展未正确调用重写的方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Swift 2协议扩展未正确调用重写的方法

不幸的是,协议还没有这样的动态行为。

但是,您可以(在类的帮助下)通过

commonBehavior()
在中实现
ParentClass
并在中进行覆盖来做到这一点
ChildClass
。您还需要一个
CommonThing
或另一个类来遵循,
CommonTrait
然后才是的超类
ParentClass

class CommonThing: CommonTrait {    func say() -> String {        return "override this"    }}class ParentClass: CommonThing {    func commonBehavior() -> String {        // calling the protocol extension indirectly from the superclass        return (self as CommonThing).commonBehavior()    }    override func say() -> String {        // if called from ChildClass the overridden function gets called instead        return commonBehavior()    }}class AnotherParentClass: CommonThing {    override func say() -> String {        return commonBehavior()    }}class ChildClass: ParentClass {    override func say() -> String {        return super.say()    }    // explicitly override the function    override func commonBehavior() -> String {        return "from child class"    }}let parent = ParentClass()parentClass.say()          // "from protocol extension"let child = ChildClass()child.say()     // "from child class"

由于这只是您问题的一个简短解决方案,我希望它适合您的项目。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/616407.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号