0Pricing
Swift Academy · Lesson

Existentials with any and Type Erasure

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

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())

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