Swift 2协议扩展没有正确调用重写方法

Swift 2协议扩展没有正确调用重写方法,第1张

概述我一直在使用 Swift 2的协议扩展和默认实现遇到问题.基本要点是我提供了一个协议方法的默认实现,我在一个实现协议的类中重写.从基类调用该协议扩展方法,然后基类调用我在派生类中重写的方法.结果是没有调用重写的方法. 我试图将这个问题提炼到最小的游乐场,这说明了下面的问题. protocol CommonTrait: class { func commonBehavior() -> Str 我一直在使用 Swift 2的协议扩展和默认实现遇到问题.基本要点是我提供了一个协议方法的默认实现,我在一个实现协议的类中重写.从基类调用该协议扩展方法,然后基类调用我在派生类中重写的方法.结果是没有调用重写的方法.

我试图将这个问题提炼到最小的游乐场,这说明了下面的问题.

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”
不幸的是,协议没有这种动态行为(尚未).

但是你可以通过在ParentClass中实现commonBehavior()并在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"

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

总结

以上是内存溢出为你收集整理的Swift 2协议扩展没有正确调用重写方法全部内容,希望文章能够帮你解决Swift 2协议扩展没有正确调用重写方法所遇到的程序开发问题。

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

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1034726.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-24
下一篇2022-05-24

发表评论

登录后才能评论

评论列表(0条)

    保存