What kinds of method dispatch does Swift have?
The idea
Dispatch is how the compiler locates a method's implementation at a call site. Swift has four kinds, from fastest to most flexible:
- Static (direct) — the function address is known at compile time. Used for struct/enum methods,
finalandstaticmembers, extension methods (except@objcones) and top-level functions. Enables inlining and other optimizations. - Table (vtable) — for overridable class methods: a class has a table of method pointers; a subclass keeps its own copy with replaced pointers. One indirect jump, no inlining without devirtualization.
- Table (witness table) — for calls through a protocol (an unspecialized generic
T: Porany P): the table records which implementation of the concrete type satisfies each protocol requirement. - Message (objc_msgSend) — through the Objective-C runtime: the method is looked up by selector at runtime. Used by
@objc dynamicmembers and by@objcmethods declared in extensions ofNSObjectsubclasses.@objcalone only exports the member to Obj-C — from Swift such a method is still called through the vtable.
Which one the compiler picks depends on the static type of the variable used for the call and on where the method is declared (type body, extension, protocol).
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep