0
0
Swiftprogramming~5 mins

Protocol inheritance in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Protocol inheritance
O(n)
Understanding Time Complexity

When using protocol inheritance in Swift, it's helpful to understand how the program's work grows as more protocols and conformances are involved.

We want to see how the time to check or use inherited protocols changes as the number of protocols grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


protocol A {
    func doA()
}

protocol B: A {
    func doB()
}

protocol C: B {
    func doC()
}

struct MyStruct: C {
    func doA() { print("A") }
    func doB() { print("B") }
    func doC() { print("C") }
}

This code shows protocols inheriting from other protocols and a struct conforming to the most derived one.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking protocol inheritance chain when accessing protocol requirements.
  • How many times: Once per level of inheritance in the protocol chain.
How Execution Grows With Input

Each time you add a new protocol that inherits from another, the program checks one more level when confirming requirements.

Input Size (n)Approx. Operations
1 (one protocol)1 check
5 (five protocols in chain)5 checks
10 (ten protocols in chain)10 checks

Pattern observation: The number of checks grows directly with the number of protocols in the inheritance chain.

Final Time Complexity

Time Complexity: O(n)

This means the time to verify or use inherited protocols grows linearly with the number of protocols in the inheritance chain.

Common Mistake

[X] Wrong: "Protocol inheritance checks happen instantly no matter how many protocols there are."

[OK] Correct: Each inherited protocol adds a step to check requirements, so more protocols mean more work.

Interview Connect

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

Self-Check

"What if a protocol inherits from multiple protocols instead of just one? How would the time complexity change?"