Middle+
How is static dispatch implemented in the Swift programming language?
sobes.tech AI
Answer from AI
Static dispatch (or direct binding) occurs when a method or function call is resolved at compile time. The compiler knows exactly which implementation of the function to call based on the variable's type. This is the fastest type of dispatch because there are no overheads for method lookup at runtime.
Static dispatch is used for:
- Structs
- Enums
- Non-marked (
final,private,fileprivate) class methods and properties - Static and class methods
- Extensions (for methods added within an extension)
- Closures
Example:
// Struct - always static dispatch
struct Point {
var x: Int
var y: Int
func description() {
// Static call to description
print("(\(x), \(y))")
}
}
let p = Point(x: 1, y: 2)
p.description()
// Class with a final method - static dispatch
final class MyClass {
func finalMethod() {
// Static call to finalMethod
print("This is a final method")
}
}
let obj = MyClass()
obj.finalMethod()
In these cases, the compiler directly inserts the address of the description or finalMethod function at the call site, bypassing the virtual method table or other dispatch mechanisms.