Type erasure for Equatable and Hashable types in Swift
Lessons from ReactiveCollectionsKit 19 February 2025
Type erasure is a method to abstract and encapsulate heterogenous generic types inside a single non-generic concrete type. In programming languages with generic types, this is a mechanism for runtime polymorphism which allows you circumvent the constraints of generics at compile time. In the early days of Swift, generics were more challenging to work with — in particular, protocols with associated types. As of Swift 5.7 (and SE-0309: Unlock existentials for all protocols), type erasure is now a feature of the Swift compiler. However, there are still situations where you may need to manually write your own type-erased wrappers.