Re-understanding Swift Protocol
🧠 Introduction
In Swift, Type Erasure is a key concept for understanding protocols and generics.
It explains why any exists and how Swift’s generic protocols differ from other languages.
1️⃣ Why Type Erasure Matters
1
2
3
4
protocol ReReduce {}
struct AppReduce: ReReduce {}
let a: any ReReduce = AppReduce()any ReReduce means “a type that conforms to ReReduce,” , but the exact type is unknown at compile time.
The compiler performs type erasure, wrapping the value in an existential container. This allows storing and calling methods on multiple conforming types in one collection.
2️⃣ Generics vs Existential Types
1
2
func process<T: Reducable>(_ value: T) { } // Generic
func process(_ value: any Reducable) { } // Existential| Feature | Generic |
Existential any |
|---|---|---|
| Type known | Compile-time | Runtime |
| Dispatch | Static (fast) | Dynamic (erased) |
| Mixed types | No | Yes |
| Use case | Performance, type safety | Polymorphism, flexibility |
Generics let the compiler know the type;
any lets it forget the type but keep its behavior.
3️⃣ Swift vs Other Languages
1
2
3
4
5
protocol ReReducer {
associatedtype S
associatedtype A
func reduce(_ state: S, _ action: A) -> S
}TypeScript equivalent:
1
2
3
interface ReReducer<S, A> {
reduce(state: S, action: A): S;
}| Feature | Swift | TypeScript / C# |
|---|---|---|
| Generic style | associatedtype | <T> |
| Type decided | At implementation/use | At declaration |
| Can store in collection | Requires type erasure | Directly supported |
Swift needs type erasure to mix generic implementations in one array.
4️⃣ Binding Associated Types
You can fix associated types using typealias to unify them:
1
2
3
4
5
6
7
typealias AnyAppReducer = any ReReducer
where S == AppState, A == AppAction
let reducers: [AnyAppReducer] = [
AppReducer(),
AnotherAppReducer()
]🧩 Summary
| Concept | Meaning |
|---|---|
| any | Declares an existential type |
| Type Erasure | Hides concrete type for flexibility |
| Generics | Compile-time, high performance |
| Existentials | Runtime, dynamic and flexible |
| associatedtype | Defines generic protocols in Swift |
- Use generics for performance and type safety.
- Use any for polymorphism and dynamic flexibility.
Understanding type erasure helps you design clearer, more adaptable Swift architectures.