Type erasure concept in Swift - Time & Space Complexity
When using type erasure in Swift, it's important to understand how the code runs as input grows.
We want to see how the number of operations changes when we use type erasure wrappers.
Analyze the time complexity of the following code snippet.
protocol Shape {
func area() -> Double
}
struct AnyShape: Shape {
private let _area: () -> Double
init(_ shape: S) {
_area = shape.area
}
func area() -> Double {
return _area()
}
}
This code wraps any Shape type inside AnyShape to hide its concrete type using type erasure.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the stored closure _area() inside AnyShape.
- How many times: Once per call to area(), no loops or recursion here.
Each call to area() runs one stored closure call, regardless of input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to _area() |
| 100 | 100 calls to _area() |
| 1000 | 1000 calls to _area() |
Pattern observation: The number of operations grows linearly with the number of calls.
Time Complexity: O(n)
This means the time grows directly in proportion to how many times you call the area() method.
[X] Wrong: "Type erasure adds hidden loops or recursion that slow down the code a lot."
[OK] Correct: Type erasure here just stores a closure and calls it once per use, so it does not add extra loops or repeated work.
Understanding how type erasure affects performance helps you explain your design choices clearly and confidently in real projects or interviews.
"What if the stored closure inside AnyShape captured a collection and iterated over it? How would the time complexity change?"