0
0
Swiftprogramming~5 mins

Protocol composition in practice in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Protocol composition in practice
O(1)
Understanding Time Complexity

When using protocol composition in Swift, it is important to understand how the program's work grows as input changes.

We want to know how combining multiple protocols affects the time it takes to run code that uses them.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


protocol A {
    func doA()
}
protocol B {
    func doB()
}

func performAction(item: A & B) {
    item.doA()
    item.doB()
}

This code defines two protocols and a function that takes an item conforming to both. It calls methods from both protocols.

Identify Repeating Operations

Look for repeated work inside the function when called with different inputs.

  • Primary operation: Calling two methods on the item.
  • How many times: Each method is called once per function call.
How Execution Grows With Input

The function calls two methods regardless of input size. If the methods themselves do not loop, the work stays the same.

Input Size (n)Approx. Operations
102
1002
10002

Pattern observation: The total work stays constant regardless of input size.

Final Time Complexity

Time Complexity: O(1)

This means the time to run stays constant regardless of input size.

Common Mistake

[X] Wrong: "Using protocol composition makes the function slower because it combines protocols."

[OK] Correct: Protocol composition itself does not add extra loops or repeated work; it just requires the item to meet multiple requirements.

Interview Connect

Understanding how protocol composition affects performance helps you write clear and efficient Swift code, a useful skill in many coding situations.

Self-Check

"What if the methods doA() and doB() each contained loops over the input? How would that change the time complexity?"