0Pricing
Swift Academy · Lesson

any P (existential): trade-offs & dynamic dispatch

Use any P to store or pass heterogeneous conformers behind a protocol. Understand dynamic dispatch, boxing, and limitations with associated types / Self requirements.

any P (existential): trade-offs & dynamic dispatch is a free Swift Academy lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What is an existential?

Existentials (any P) hold any value conforming to P. They enable heterogenous storage and dynamic dispatch, with some restrictions.

  • Great for mixed collections
  • Dynamic dispatch via protocol witness tables
  • Limitations with associated types/Self

Heterogeneous collection

any Shape lets you store different conformers together and call protocol methods via dynamic dispatch.

protocol Shape { func area() -> Double }

struct Circle: Shape { let r: Double; func area() -> Double { .pi * r * r } }
struct Square: Shape { let s: Double; func area() -> Double { s * s } }

// Heterogeneous array using ANY Shape
let shapes: [any Shape] = [Circle(r: 1), Square(s: 2), Circle(r: 0.5)]
let total = shapes.reduce(0) { $0 + $1.area() }   // dynamic dispatch
print(String(format: "%.2f", total))

Interface boundary

Existentials expose only the protocol interface. Concrete-only methods require downcasting (which is optional and runtime-checked).

extension Circle { func diameter() -> Double { 2 * r } }

let mixed: [any Shape] = [Circle(r: 1), Square(s: 3)]
print(mixed[0].area())            // OK: in protocol
// print(mixed[0].diameter())     // ❌ Not visible via any Shape (commented)
// You'd need a type check / downcast:
if let c = mixed[0] as? Circle { print(c.diameter()) }

Associated type caveat

Existentials cannot carry unknown associated types or Self-referential requirements directly. Use type erasure or fix the associated type via a wrapper.

// Protocols with associated types/Self constraints can be hard to use as existentials.
protocol Parser {
    associatedtype Output
    func parse(_ s: String) -> Output
}

// let p: any Parser = ...     // ❌ Not directly usable: Output is unknown
// Workarounds: type erasure or constrain Output to a specific type in wrappers.

Choosing the parameter style

Existential: heterogeneous & flexible. Generic: homogeneous & faster/checked at compile time. Pick per need.

// Existential: accepts any mix of Shapes (dynamic dispatch)
func totalAreaExistential(_ xs: [any Shape]) -> Double {
    xs.reduce(0) { $0 + $1.area() }
}

// Generic (homogeneous): static dispatch; one concrete Shape type per call
func totalAreaGeneric<S: Sequence, T: Shape>(_ xs: S) -> Double
where S.Element == T {
    xs.reduce(0) { $0 + $1.area() }
}

print(totalAreaExistential([Circle(r:1), Square(s:2)]))  // mixed OK
print(totalAreaGeneric([Circle(r:1), Circle(r:2)]))      // homogeneous only
// totalAreaGeneric([Circle(r:1), Square(s:2)])          // ❌ different types

When to use any P

Guidelines:

  • Use any P for heterogeneous storage and runtime polymorphism.
  • Prefer generics for performance and static guarantees when elements are homogeneous.
  • Avoid existentials for protocols with associated types/Self unless you type-erase or wrap.

Existential benefit

Quick check: What does any P enable?

Recap

Recap: any P = existential container for protocol-conforming values. It enables heterogeneous polymorphism via dynamic dispatch but hides concrete-only APIs and struggles with associated types/Self.

Frequently asked questions

Is the “any P (existential): trade-offs & dynamic dispatch” lesson free?

Yes — the full text of “any P (existential): trade-offs & dynamic dispatch” is free to read here on the web, and the Swift Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “any P (existential): trade-offs & dynamic dispatch”?

Use any P to store or pass heterogeneous conformers behind a protocol. Understand dynamic dispatch, boxing, and limitations with associated types / Self requirements. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “any P (existential): trade-offs & dynamic dispatch” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. some P (opaque result types): hiding concrete types
  2. any P (existential): trade-offs & dynamic dispatch
  3. Choosing between some, any, and generics
← Back to Swift Academy