What if you could treat many different things as one without losing what makes each special?
Why Type erasure concept in Swift? - Purpose & Use Cases
Imagine you have different kinds of boxes, each holding a different type of toy. You want to put all these boxes on one shelf, but the shelf only accepts boxes of the same type. You try to manually wrap each box to look the same, but it quickly becomes confusing and messy.
Manually handling different types means writing lots of repetitive code to treat each type separately. It's slow, error-prone, and hard to maintain. You lose flexibility because you can't easily mix different types in one place without complex workarounds.
Type erasure acts like a universal wrapper that hides the specific type inside, making all boxes look the same to the shelf. This lets you store and use different types together seamlessly, without losing the unique behavior of each type.
func printAll<T>(items: [T]) { for item in items { print(item) } } // But T must be same typestruct AnyBox { private let _print: () -> Void; init<T>(_ box: T) { _print = { print(box) } } func printBox() { _print() } }It enables writing flexible, reusable code that can handle many different types uniformly without losing their unique features.
In SwiftUI development, you might want to store different views in one list. Type erasure lets you wrap each view so they can all be treated as the same type, making your UI code simpler and cleaner.
Manual handling of multiple types is complex and error-prone.
Type erasure hides specific types behind a common interface.
This allows flexible and clean code that works with many types together.