gpt4 book ai didi

Swift 2 协议(protocol)扩展没有正确调用覆盖的方法

转载 作者:IT王子 更新时间:2023-10-29 05:50:12 26 4
gpt4 key购买 nike

我在使用带有默认实现的 Swift 2 协议(protocol)扩展时遇到了一个问题。基本要点是我提供了一个协议(protocol)方法的默认实现,我在实现该协议(protocol)的类中重写了该方法。从基类调用该协议(protocol)扩展方法,然后基类调用我在派生类中重写的方法。结果是未调用覆盖的方法。

我试图将问题提炼到最小的可能的 Playground 上,这说明了下面的问题。

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)还没有这样的动态行为。

但您可以通过在 ParentClass 中实现 commonBehavior() 并在 ChildClass 中覆盖它来做到这一点(在类的帮助下) .您还需要 CommonThing 或另一个类来符合 CommonTrait ,它是 ParentClass 的父类(super class):

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 协议(protocol)扩展没有正确调用覆盖的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31795158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com