SwiftPumpkin

9 of 22 · 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

ConformsConformsProtocolRequirements + default implsstruct CardConformsstruct PoemConforms, overrides
calls or tellsreports backBehavior comes from protocol extensions, not a base class. Value types stay value types.
  • Protocols plus extensions give shared behavior to structs and enums.
  • Generics (some P) keep it fast and type-safe.
PartOwnsLooks like
ProtocolDeclare requirementsprotocol ThanksFormatter
ExtensionDefault implementationsextension ThanksFormatter
ConformersValue types adopting behaviorstruct, enum
Generic useStatic dispatch at call sitesfunc render(_ f: some ThanksFormatter)

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 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 seamSwapping storage, network or clock in tests and features.
Shared behavior across unrelated typesProtocol plus extension defaults.
One implementation, no seamA concrete type. No protocol.

Compared

Inheritance vs some P vs any P

Inheritancesome Pany P
DispatchDynamic (vtable)Static when specialized, else witness tableDynamic (witness table)
Mixed types in one arrayYesNoYes
Value typesNoYesYes
Runtime costReference semanticsLowestBox + 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.

30-second answer

Explain Protocol-Oriented Programming in 30 seconds.

SwiftAsked directly

some versus any: what's the real difference, and which should be your default?

SwiftAsked indirectly

A function returns a long nested generic type that leaks implementation details. How do you hide it without losing performance?

SwiftAsked indirectly

A type implements a method that also lives in a protocol extension, yet the extension's version runs. Why?

Read it in the app's source