0
0
Swiftprogramming~5 mins

Protocol as types in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Protocol as types
O(n)
Understanding Time Complexity

When we use protocols as types in Swift, we want to know how the program's running time changes as we work with more objects that follow the protocol.

We ask: How does the time to call protocol methods grow when we have many such objects?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


protocol Drawable {
    func draw()
}

func drawAll(shapes: [Drawable]) {
    for shape in shapes {
        shape.draw()
    }
}
    

This code defines a protocol and a function that calls the draw method on each object in a list of protocol types.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling draw() on each object in the array.
  • How many times: Once for each object in the shapes array.
How Execution Grows With Input

As the number of shapes grows, the total calls to draw() grow the same way.

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

Pattern observation: The number of operations grows directly with the number of shapes.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the function grows in a straight line as you add more shapes.

Common Mistake

[X] Wrong: "Using a protocol as a type makes the code slower in a way that changes the time complexity."

[OK] Correct: Calling methods on protocol types does add a small fixed cost, but this cost stays the same per call and does not change how the total time grows with more objects.

Interview Connect

Understanding how using protocols as types affects performance helps you explain your design choices clearly and shows you know how code structure relates to speed.

Self-Check

What if the draw() method itself contained a loop over a collection? How would that change the overall time complexity?