0
0
Swiftprogramming~3 mins

Why Type erasure concept in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could treat many different things as one without losing what makes each special?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
func printAll<T>(items: [T]) { for item in items { print(item) } } // But T must be same type
After
struct AnyBox { private let _print: () -> Void; init<T>(_ box: T) { _print = { print(box) } } func printBox() { _print() } }
What It Enables

It enables writing flexible, reusable code that can handle many different types uniformly without losing their unique features.

Real Life Example

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.

Key Takeaways

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.