Protocol conformance via extension in Swift - Time & Space Complexity
When a Swift type adopts a protocol through an extension, it gains new behavior. We want to understand how the time it takes to use that behavior changes as input grows.
How does the program's work grow when calling protocol methods added by extensions?
Analyze the time complexity of the following code snippet.
protocol Summable {
func sum() -> Int
}
extension Array: Summable where Element == Int {
func sum() -> Int {
var total = 0
for number in self {
total += number
}
return total
}
}
let numbers = [1, 2, 3, 4, 5]
let result = numbers.sum()
This code adds a sum() method to arrays of integers using a protocol extension. It calculates the total of all numbers in the array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the array to add it to a total.
- How many times: Once for every element in the array (n times, where n is the array size).
As the array gets bigger, the method does more additions, one per element.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of elements. Double the elements, double the work.
Time Complexity: O(n)
This means the time to compute the sum grows linearly with the number of items in the array.
[X] Wrong: "Adding a method via protocol extension makes the code run instantly regardless of input size."
[OK] Correct: Even though the method is added by extension, it still processes each element one by one, so the time depends on input size.
Understanding how protocol extensions affect performance helps you explain your code choices clearly and shows you know how Swift handles behavior and efficiency together.
What if the sum() method used recursion instead of a loop? How would the time complexity change?