7 of 20 · System architecture
Protocol-Oriented Programming
Protocol-oriented programming models shared behavior as protocols with default implementations in extensions, so value types gain behavior by conformance instead of inheriting from a base class.
How it's wired
- Protocols plus extensions give shared behavior to structs and enums.
- Generics (some P) keep it fast and type-safe.
| Part | Owns | Looks like |
|---|---|---|
| Protocol | Declare requirements | protocol ThanksFormatter |
| Extension | Default implementations | extension ThanksFormatter |
| Conformers | Value types adopting behavior | struct, enum |
| Generic use | Static dispatch at call sites | func render(_ f: some ThanksFormatter) |
Swift example: static dispatch trap and some vs any
Two protocol behaviors that surprise even experienced Swift engineers.
Extension-only method trap + some vs any
Methods missing from the protocol declaration dispatch statically through the existential, ignoring the concrete override.
protocol NoteFormatting: Sendable {
func title(for note: ThankYouNote) -> String
}
extension NoteFormatting {
// Not declared in the protocol: dispatched STATICALLY when called via `any NoteFormatting`.
func badge() -> String { "default" }
}
struct WarmFormatter: NoteFormatting {
func title(for note: ThankYouNote) -> String { "Thanks, \(note.recipient)" }
func badge() -> String { "warm" }
}
// Prefer `some`: specialized at compile time, no existential heap box.
func render<F: NoteFormatting>(_ note: ThankYouNote, with formatter: F) -> String {
formatter.title(for: note)
}
// Use `any` only when you genuinely need heterogeneous storage.
let formatters: [any NoteFormatting] = [WarmFormatter()]
// formatters[0].badge() returns "default", NOT "warm"!If a method should be customizable by conformers, declare it in the protocol itself.
Where it gets subtle
- Dispatch: a method declared only in an extension, not in the protocol, dispatches statically. Calling it through the protocol type ignores a conformer's own version. It's a classic bug.
- some P is one concrete type fixed at compile time: specialized and fast. any P is an existential box (a runtime wrapper holding the value, type metadata and witness table) with dynamic dispatch and possible heap allocation. Default to some.
- Associated types make protocols powerful and awkward as values. Reach for generics or primary associated types (any Collection<Int>) before writing type erasers.
- Don't create a protocol per class "for testing". If there's one implementation and no seam is needed, skip the protocol.
When I reach for protocols
| A real seam | Swapping storage, network or clock in tests and features. |
|---|---|
| Shared behavior across unrelated types | Protocol plus extension defaults. |
| One implementation, no seam | A concrete type. No protocol. |
Compared
Inheritance vs some P vs any P
| Inheritance | some P | any P | |
|---|---|---|---|
| Dispatch | Dynamic (vtable) | Static when specialized, else witness table | Dynamic (witness table) |
| Mixed types in one array | Yes | No | Yes |
| Value types | No | Yes | Yes |
| Runtime cost | Reference semantics | Lowest | Box + indirection |
Expert notes
- Protocols are seams. Put them where you need to swap or test something, and nowhere else.
Check yourself
Answer out loud before you reveal. Recall is what makes it stick.
Explain Protocol-Oriented Programming in 30 seconds.
- Protocol-oriented programming puts shared behavior in protocols with default implementations, so structs and enums gain behavior without a base class.
- The value I care about is the seam: a feature depends on a small protocol, which lets storage or a vendor SDK change behind it and lets tests pass fakes.
- The cost is indirection, since readers jump through more files to find what runs.
- I add a protocol only where something actually varies, and never one per class by reflex.
some versus any: what's the real difference, and which should be your default?
- I default to
some Por generics, and useany Pwhen the concrete type really varies at runtime. - An
any Pis an existential box, which may heap-allocate and keeps calls from being specialized. - The explicit
anykeyword exists to make that cost visible. some Pkeeps the concrete type known to the compiler, so it can specialize and inline.- For an injected service doing I/O, I'd still accept
any, because the box costs little next to the work behind it.
A function returns a long nested generic type that leaks implementation details. How do you hide it without losing performance?
- Return an opaque type, like
func makeShape() -> some Shape. - Callers only see the protocol, but the compiler keeps the concrete type, so generic code still optimizes. That's the difference from an existential.
- The constraint is that every return path must produce the same concrete type.
- If branches differ, you need a type-erasing wrapper or a result builder.
A type implements a method that also lives in a protocol extension, yet the extension's version runs. Why?
- Only protocol requirements are dynamically dispatched.
- A method that exists only in a protocol extension is statically dispatched, so calling through the protocol type runs the extension's version and skips the type's own.
- Fix it by declaring the method in the protocol, like
protocol Greeter { func greet() }, and keeping the extension as the default implementation.
Read it in the app's source
Done with Protocol-Oriented Programming? Mark it complete. Nailing its cards builds this pumpkin, row by row.