This is a very similar question: Calling protocol default implementation from regular method, BUT none of the answers cover the case when inherance plays a role. The answer suggest casting it to the protocol type itself will solve it, but not in this case (Copy paste in playground):
public protocol MyProtocol {
func sayCheese()
}
public extension MyProtocol {
func sayHi() {
print("Hi, I am protocol")
sayCheese()
}
func sayCheese() {
print("Cheese from protocol")
}
}
public class MyFirstClass: MyProtocol {
public func sayCheese() {
print("Cheese from 1")
(self as MyProtocol).sayCheese()
}
}
public class MySecondClass: MyFirstClass {
override init() {
super.init()
sayHi()
}
public func sayHi() {
print("Hi from 2")
super.sayHi()
}
public override func sayCheese() {
print("Said cheese from 2")
super.sayCheese()
}
}
MySecondClass()
It prints the following:
...
Said cheese from 2
Cheese from 1
Said cheese from 2
Cheese from 1
...
In instance of MyFirstClass
, how can I call the default implementation of MyProtocol of method sayCheese
?
Edit: My usecase is the following:
I have a protocol which is adopted by a class, which is subclassed a lot. The protocol has multiple default methods, which can call eachother. Some of the subclasses needs to override the methods, do stuff, and call super.method()
(to finally call the default implementation of the protocol, because a superclass may have overriden the protocol default implementation as well). So I really need dynamic dispatching.