0
0
Swiftprogramming~5 mins

Existential types (any keyword) in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Existential types (any keyword)
O(n)
Understanding Time Complexity

We want to understand how using existential types with the any keyword affects the time it takes for a program to run.

Specifically, we ask: How does the program's work grow when we use any types with different input sizes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


protocol Drawable {
    func draw()
}

func drawAll(_ items: [any Drawable]) {
    for item in items {
        item.draw()
    }
}

// Usage:
// let shapes: [any Drawable] = [Circle(), Square(), ...]
// drawAll(shapes)
    

This code calls the draw() method on each item in an array of existential types.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the array and calling draw() on each element.
  • How many times: Once for each element in the input array.
How Execution Grows With Input

As the number of items grows, the number of draw() calls grows the same way.

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

Pattern observation: The work grows directly in proportion to the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows linearly with the number of items in the array.

Common Mistake

[X] Wrong: "Using any types makes the loop slower in a way that changes the overall time complexity."

[OK] Correct: While any types add some small overhead for dynamic dispatch, the number of operations still grows linearly with input size, so the overall time complexity remains O(n).

Interview Connect

Understanding how existential types affect performance helps you explain trade-offs clearly and shows you can reason about code efficiency in real projects.

Self-Check

What if we changed the array to hold concrete types instead of any Drawable? How would the time complexity change?