Sobes.tech
Junior — Middle

What dispatching mechanism is used when calling a method defined in a protocol that has been extended using Extension?

sobes.tech AI

Answer from AI

In Swift, if a method is defined in a protocol and then the protocol is extended via an Extension with an implementation of that method, calling the method through a protocol reference uses static dispatch. This means that the method call will be directed to the implementation in the protocol extension, not the implementation in the specific type, even if the type overrides it.

In other words, methods implemented in protocol extensions do not support dynamic dispatch, unlike required protocol methods implemented in types.

Example:

protocol MyProtocol {
    func requiredMethod()
}

extension MyProtocol {
    func requiredMethod() {
        print("Default implementation in extension")
    }
}

struct MyStruct: MyProtocol {
    func requiredMethod() {
        print("Implementation in MyStruct")
    }
}

let instance: MyProtocol = MyStruct()
instance.requiredMethod() // Will print "Default implementation in extension"

This is because methods from protocol extensions are not part of the virtual table (vtable) and are called directly.