What dispatching is used for extensions in Swift?
sobes.tech AI
Answer from AI
Dispatching for methods implemented in extensions depends on the type of extension and the nature of the called method:
-
Virtual Dispatch (Dynamic Dispatch): Used for methods defined in protocols and extensions to those protocols, when the method is called through a variable of the protocol type. Also applied to extension methods for classes.
-
Static Dispatch (Static Dispatch): Used for methods defined in extensions to structures and enumerations. The call to such functions is determined at compile time.
-
Mixed Dispatch (Witness Table): For extensions to protocols with default implementations. If the type conforming to the protocol already implements the method, its implementation will be used (virtual dispatch). Otherwise, the implementation from the extension via the Witness Table will be called (similar to static dispatch, but for protocols).
Example:
// Extension to a class - virtual dispatch when called through a variable of the base type
class BaseClass {
}
extension BaseClass {
func virtualMethod() {
print("BaseClass extension")
}
}
class DerivedClass: BaseClass {
// Overriding the extension method is possible but not common practice
// override func virtualMethod() { print("DerivedClass extension") }
}
// Extension to a struct - static dispatch
struct MyStruct {
}
extension MyStruct {
func staticMethod() {
print("MyStruct extension")
}
}
// Extension to a protocol
protocol MyProtocol {
func protocolMethod()
}
extension MyProtocol {
func protocolMethod() { // Default implementation
print("Default protocol implementation")
}
}
struct ConformingStruct: MyProtocol {
// If uncommented, this implementation will be called
// func protocolMethod() { print("ConformingStruct implementation") }
}
Dispatching in class extensions can also be explicitly specified using the @objc and @nonobjc attributes for interaction with the Objective-C runtime and management of the virtual table.