How is the dispatching of methods added through Extension in protocols implemented?
sobes.tech AI
Answer from AI
Methods added through Extensions in Swift protocols are implemented using static dispatch. This means that the call to such methods is determined at compile time, not at runtime. Unlike methods declared directly in the protocol (which use dynamic dispatch via the virtual method table), methods from extensions cannot be overridden in specific types and are called directly by the type known at compile time.
For example, if you have a protocol and an extension with a method, and then a type that implements this protocol, calling the method from the extension will always use the implementation from the extension, even if the type implements a method with the same name. This is because extensions do not add methods to the protocol's virtual method table.
protocol MyProtocol {}
extension MyProtocol {
func greet() {
print("Hello from extension")
}
}
struct MyStruct: MyProtocol {
func greet() {
print("Hello from MyStruct")
}
}
let obj: MyProtocol = MyStruct()
obj.greet() // Will print: Hello from extension
let obj2 = MyStruct()
obj2.greet() // Will print: Hello from MyStruct
Thus, methods from protocol extensions are called statically, which is important to consider when designing architecture.