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. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.
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 infoType 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 OKPrefer 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 automaticallyType 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 typeQuick 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.
Learn Swift with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 122
- Lessons
- 409
Frequently Asked Questions
Is the “Existentials with any and Type Erasure” lesson free?
Yes — any 3 lessons of the Swift Academy learning path, including “Existentials with any and Type Erasure”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.
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
- Generic Constraints and where Clauses
- Opaque Types with some Keyword
- Existentials with any and Type Erasure
- Primary Associated Types and Typed Throws