From the post The Ghost of Swift Bugs Future, here are the rules for dispatch for protocol extensions that are mentioned at the end of the post.
- IF the inferred type of a variable is the protocol:
- AND the method is defined in the original protocol THEN the
runtime type’s implementation is called, irrespective of whether
there is a default implementation in the extension.
- AND the method is not defined in the original protocol, THEN the
default implementation is called.
- ELSE IF the inferred type of the variable is the type THEN the type’s implementation is called.
So in your condition, you're saying that method1() is defined in the protocol and it has been implemented in the subclass. But your superclass is adopting the protocol but it is not implementing the method1() and subclass just inherits from the Superclass and doesn't adopt to the protocols directly. That's why I believe that is the reason when you call foo.method1(), it doesn't invoke the the subclass implementation as stated by point 1 & 2.
But when you do,
class SomeSuperclass: TheProtocol {
func method1(){
print("super class implementation of method1()")}
}
class MyClass : SomeSuperclass {
override func method1() {
print("Called method1 from MyClass implementation")
}
override func method2NotInProtocol() {
print("Called method2NotInProtocol from MyClass implementation")
}
}
and then when you call,
let foo: TheProtocol = MyClass()
foo.method1() // Called method1 from MyClass implementation
foo.method2NotInProtocol()
So what could be the workaround for this bug (which seems to be a bug) is that, you need to implement the protocol method in the superclass and then you need to override the protocol method in the sub class. HTH
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…