Protocol as types in Swift - Time & Space 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?
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 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
shapesarray.
As the number of shapes grows, the total calls to draw() grow the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to draw() |
| 100 | 100 calls to draw() |
| 1000 | 1000 calls to draw() |
Pattern observation: The number of operations grows directly with the number of shapes.
Time Complexity: O(n)
This means the time to run the function grows in a straight line as you add more shapes.
[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.
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.
What if the draw() method itself contained a loop over a collection? How would that change the overall time complexity?