DevPrep

All topics › The Swift Language

What is type erasure and why is it needed?

Senior PRO

The idea

Type erasure hides a concrete type behind a common interface so that different implementations of a protocol can be treated as one type: stored in one array or property, returned from a function, without exposing the implementation.

Historically (before Swift 5.7) a protocol with an associatedtype or Self could not be used as a type at all, so wrappers like AnySequence, AnyPublisher and AnyView were written by hand. Today the language does most of this itself.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store