0
0
Swiftprogramming~5 mins

Type erasure concept in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Type erasure concept
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each call to area() runs one stored closure call, regardless of input size.

Input Size (n)Approx. Operations
1010 calls to _area()
100100 calls to _area()
10001000 calls to _area()

Pattern observation: The number of operations grows linearly with the number of calls.

Final Time Complexity

Time Complexity: O(n)

This means the time grows directly in proportion to how many times you call the area() method.

Common Mistake

[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.

Interview Connect

Understanding how type erasure affects performance helps you explain your design choices clearly and confidently in real projects or interviews.

Self-Check

"What if the stored closure inside AnyShape captured a collection and iterated over it? How would the time complexity change?"