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
- Generic Constraints and where Clauses
- Opaque Types with some Keyword
- Existentials with any and Type Erasure
- Primary Associated Types and Typed Throws