0Pricing
Swift Academy · Lesson

Existentials with any and Type Erasure

Using any Protocol, the performance cost and when to prefer generics.

Existentials with any and Type Erasure is a free Swift Academy lesson on CoddyKit — lesson 3 of 4. 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 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What is an Existential?

An existential type boxes any value conforming to a protocol behind a uniform interface, resolved at runtime.

protocol Drawable { func draw() }
struct Line: Drawable { func draw() { print("Line") } }
let d: any Drawable = Line()
d.draw()

The any Keyword

Swift 5.7 requires the any keyword before protocol names used as existential types to make the boxing explicit.

func render(_ shape: any Drawable) {
  shape.draw()
}
render(Line())

Existential Cost

Existentials use heap allocation and dynamic dispatch, which can be slower than generics with static dispatch.

// Existential – dynamic dispatch, potential heap alloc
var shapes: [any Drawable] = [Line(), Line()]
// Generic – static dispatch, no boxing
func drawGeneric<T: Drawable>(_ s: T) { s.draw() }

PATs and Existentials Problem

Protocols with associated types (PATs) cannot be used as bare existentials without type erasure.

protocol Container { associatedtype Item }
// var c: any Container // Swift 5.7 allows with "any" but loses Item info

Type Erasure Pattern

A type-erased wrapper wraps a concrete type behind a struct, hiding the concrete type.

struct AnyDrawable: Drawable {
  private let _draw: () -> Void
  init<D: Drawable>(_ d: D) { _draw = d.draw }
  func draw() { _draw() }
}

AnySequence and AnyPublisher

Swift stdlib and Combine ship type-erased wrappers like AnySequence and AnyPublisher.

import Combine
let subject = PassthroughSubject<Int, Never>()
let pub: AnyPublisher<Int, Never> = subject.eraseToAnyPublisher()

eraseToAnyPublisher()

eraseToAnyPublisher() hides the concrete publisher chain so callers depend only on AnyPublisher.

func fetch() -> AnyPublisher<String, Error> {
  URLSession.shared.dataTaskPublisher(for: URL(string: "https://example.com")!)
    .map { String(data: $0.data, encoding: .utf8) ?? "" }
    .eraseToAnyPublisher()
}

When Existentials are Appropriate

Use existentials for heterogeneous collections or when the exact type is unknown at compile time.

var widgets: [any Drawable] = [] // mixed concrete types OK

Prefer Generics over Existentials

When possible, replace existentials with generics to gain static dispatch and performance.

// Prefer this:
func draw<T: Drawable>(_ item: T) { item.draw() }
// Over this:
func draw(_ item: any Drawable) { item.draw() }

Opening Existentials

Swift 5.7+ can "open" an existential when calling a generic function, automatically extracting the underlying type.

func drawGeneric<T: Drawable>(_ d: T) { d.draw() }
let d: any Drawable = Line()
drawGeneric(d) // compiler opens the existential automatically

Type Erasure vs Opaque Types

Type erasure hides type for heterogeneous use; opaque types preserve identity for a single consistent return type.

let erased: any Drawable = Line()   // runtime type unknown
let opaque: some Drawable = Line()   // compile-time fixed type

Quick Check

What is the primary performance cost of existential types?

Lesson Recap

Existentials (any Protocol) enable runtime polymorphism at the cost of dynamic dispatch. Type erasure wraps concrete types behind a stable interface. Prefer generics for performance; use existentials for heterogeneous collections.

Frequently asked questions

Is the “Existentials with any and Type Erasure” lesson free?

Yes — the full text of “Existentials with any and Type Erasure” is free to read here on the web, and the Swift Academy course includes 4 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 “Existentials with any and Type Erasure”?

Using any Protocol, the performance cost and when to prefer generics. 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 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Existentials with any and Type Erasure” 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. Generic Constraints and where Clauses
  2. Opaque Types with some Keyword
  3. Existentials with any and Type Erasure
  4. Primary Associated Types and Typed Throws
← Back to Swift Academy