1.11 · Static vs dynamic dispatch
Every call has to be resolved. The question is when — compile time or runtime — and that single answer explains performance, overriding, and the “my method never ran” bug.
Mental model. Static = the compiler already knows. Dynamic = something is only known at runtime: a subclass, an existential, or an Objective-C receiver.
Static vs dynamic
How a call finds its implementation.
- Static vs dynamic dispatch in Swift?
Static — the compiler knows the exact implementation: structs, enums, generics after specialization, final classes, and protocol extension methods that are not… - Why does
final(and whole-module optimization) help performance?
final tells the compiler no subclass can override the method, so it can devirtualize the call into a direct one — and then inline it. Whole-module optimization…
The protocol extension trap
Same call, different method, depending on the static type.
- You added a method in a protocol extension and overrode it on a concrete type, but calling through
any Pdoes not hit your override. Why?
Because the method is not a protocol requirement. Only requirements get a slot in the witness table. A method that exists only in an extension is a plain…
More in Swift language
- 1.1 · Value vs reference types
- 1.2 · Optionals, pattern matching, control flow
- 1.3 · Protocols, extensions, associated types
- 1.4 · Generics, <code>some</code>, <code>any</code>
- 1.5 · Closures, escaping, capture lists
- 1.6 · Properties, observers, wrappers
- 1.7 · Access control
- 1.8 · Error handling, <code>defer</code>, ownership
- 1.9 · Strings and Unicode
- 1.10 · Codable, Sendable, macros, ABI