0
0
Swiftprogramming~5 mins

Protocol conformance via extension in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Protocol conformance via extension
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

As the array gets bigger, the method does more additions, one per element.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the number of elements. Double the elements, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to compute the sum grows linearly with the number of items in the array.

Common Mistake

[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.

Interview Connect

Understanding how protocol extensions affect performance helps you explain your code choices clearly and shows you know how Swift handles behavior and efficiency together.

Self-Check

What if the sum() method used recursion instead of a loop? How would the time complexity change?