I've been running into an issue using Swift 2's protocol extensions with default implementations. The basic gist is that I've provided a default implementation of a protocol method which I am overriding in a class that implements the protocol. That protocol extension method is being called from a base class, which is then calling a method which I have overridden in a derived class. The result is that the overridden method is not being called.
I've tried to distill the problem to the smallest possible playground which illustrates the issue below.
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”
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…