Protocol extensions for shared behavior in Swift - Time & Space Complexity
We want to understand how adding shared behavior through protocol extensions affects the time it takes for code to run.
Specifically, how does the number of operations grow when using protocol extensions in Swift?
Analyze the time complexity of the following code snippet.
protocol Greetable {
func greet()
}
extension Greetable {
func greet() {
print("Hello from protocol extension!")
}
}
struct Person: Greetable {}
let people = Array(repeating: Person(), count: n)
for person in people {
person.greet()
}
This code defines a protocol with a default greeting method, creates many Person instances conforming to it, and calls greet on each.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling
greet()on each element in the array. - How many times: Exactly
ntimes, once per element.
Each additional person adds one more call to greet(). So the total work grows directly with the number of people.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 greet calls |
| 100 | 100 greet calls |
| 1000 | 1000 greet calls |
Pattern observation: The work grows in a straight line as the input size increases.
Time Complexity: O(n)
This means the time to run grows directly in proportion to how many items we have.
[X] Wrong: "Using protocol extensions makes the code run slower because it adds extra layers."
[OK] Correct: Protocol extensions provide shared behavior without adding extra loops or nested calls; the main cost is still just calling the method once per item.
Understanding how protocol extensions affect performance shows you can write clean code without worrying about hidden slowdowns, a skill valuable in real projects and interviews.
"What if the greet() method inside the protocol extension called another method that loops over a collection? How would the time complexity change?"