0
0
Swiftprogramming~5 mins

Protocol extensions with default implementations in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Protocol extensions with default implementations
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code changes when using protocol extensions with default implementations in Swift.

Specifically, we ask: How does adding default methods in protocol extensions affect the speed as the program runs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


protocol Greetable {
    func greet()
}

extension Greetable {
    func greet() {
        print("Hello from default implementation")
    }
}

struct Person: Greetable {}

let n = 10
let people = Array(repeating: Person(), count: n)
for person in people {
    person.greet()
}
    

This code defines a protocol with a default greet method, creates many Person instances, and calls greet on each.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the greet() method on each Person instance.
  • How many times: Exactly once for each element in the people array, which has n elements.
How Execution Grows With Input

As the number of people grows, the number of greet calls grows the same way.

Input Size (n)Approx. Operations
1010 greet calls
100100 greet calls
10001000 greet calls

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of elements we process.

Common Mistake

[X] Wrong: "Using protocol extensions with default methods makes the code slower because it adds extra layers."

[OK] Correct: The default method is called just like any other method, so the time to run depends mainly on how many times you call it, not on it being a default implementation.

Interview Connect

Understanding how default methods in protocols affect performance helps you write clean, reusable code without worrying about hidden slowdowns.

Self-Check

"What if the greet method was overridden in Person with a more complex operation? How would the time complexity change?"