Fast, high-signal Swift cheat sheets for everyday reference. These pages are sourced from cheat-sheets/ and stay in sync with the repo—scan the list below or search to find the snippet you need.
Dispatch (Swift) 1. What is it? Dispatch is the mechanism that decides which implementation a call will execute (and when that decision is made: compile-time vs runtime). In Swift, dispatch choices directly affect polymorphism, correctness (especially with protocol extensions), and performance. 2. What problem does it solve? Enables polymorphism (same call, different behavior) via inheritance or protocols. Balances flexibility vs performance (dynamic lookup vs direct calls). Defines how overrides, protocol conformances, and runtime features (KVO/swizzling) work. 3. Types / Categories Kind Trigger / Where it appears Mechanism Typical cost Notes Static dispatch (direct call) struct/enum, final methods/classes, static functions, many generics Compiler emits a direct call Lowest Most optimizable (inline, specialize) Virtual dispatch (vtable) class inheritance + overridable methods vtable lookup Low–medium Enables override polymorphism Protocol dispatch (witness table) Calling protocol requirements through a protocol type witness table lookup Low–medium Key for any Protocol calls Obj-C message dispatch @objc dynamic, KVC/KVO, swizzling, selectors objc_msgSend Medium–high Most dynamic, least optimizable 4. How does it work in Swift? Quick decision tree Value types (struct/enum) → usually static dispatch final class or final func → static dispatch (cannot be overridden) Non-final class methods (especially overridden) → vtable dispatch Protocol requirement calls via any Protocol → witness table dispatch Protocol extension methods → static dispatch (common footgun) Generic T: Protocol → often specialized by the compiler → can become close to static dispatch @objc dynamic → Objective-C runtime dispatch (objc_msgSend) Why protocol extensions can surprise you A method implemented in a protocol extension is not always dispatched through the witness table. If you call it via an existential (let x: any P = ...), Swift may bind to the extension implementation (static) instead of the conforming type’s method (dynamic through witness table). Rule of thumb: ...