Protocol requirements (methods and properties) in Swift - Time & Space Complexity
When using protocols with required methods and properties, it's important to know how the time to run code changes as the program grows.
We want to see how the number of operations grows when calling these protocol requirements.
Analyze the time complexity of the following code snippet.
protocol Drawable {
func draw()
var color: String { get }
}
func renderAll(drawables: [Drawable]) {
for item in drawables {
item.draw()
print(item.color)
}
}
This code defines a protocol with a method and a property, then calls them on each item in a list.
Look for loops or repeated calls.
- Primary operation: Looping through the array and calling
draw()and accessingcoloron each item. - How many times: Once for each item in the
drawablesarray.
As the number of items grows, the number of calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 calls to draw() and 10 property accesses |
| 100 | About 100 calls to draw() and 100 property accesses |
| 1000 | About 1000 calls to draw() and 1000 property accesses |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items.
[X] Wrong: "Calling protocol methods is slower and adds extra loops behind the scenes."
[OK] Correct: Calling a protocol method or property is just like calling any method once per item; it does not add hidden loops or extra repeated work.
Understanding how protocol requirements affect performance helps you explain your code choices clearly and confidently in real projects.
What if the draw() method itself contained a loop over another collection? How would that change the time complexity?