Protocol inheritance in Swift - Time & Space 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.
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 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.
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.
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.
[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.
Understanding how protocol inheritance affects performance helps you write clear and efficient Swift code, a skill valuable in many coding situations.
"What if a protocol inherits from multiple protocols instead of just one? How would the time complexity change?"