Protocol composition in Swift - Time & Space Complexity
When using protocol composition in Swift, it's important to understand how combining multiple protocols affects the time it takes to check if a type conforms to all of them.
We want to know how the time to verify protocol conformance grows as we add more protocols to the composition.
Analyze the time complexity of checking conformance to a composed protocol.
protocol A { func doA() }
protocol B { func doB() }
protocol C { func doC() }
func checkConformance(_ obj: Any) {
if let obj = obj as? A & B & C {
obj.doA()
obj.doB()
obj.doC()
}
}
This code checks if an object conforms to three protocols combined using protocol composition.
Look at what happens when Swift checks protocol conformance:
- Primary operation: Checking each protocol in the composition one by one.
- How many times: Once for each protocol in the composition (here, 3 times).
As you add more protocols to the composition, the number of checks grows directly with the number of protocols.
| Number of Protocols (n) | Approx. Checks |
|---|---|
| 3 | 3 |
| 10 | 10 |
| 100 | 100 |
Pattern observation: The time to check grows in a straight line as you add more protocols.
Time Complexity: O(n)
This means the time to check protocol composition grows proportionally with the number of protocols combined.
[X] Wrong: "Checking protocol composition is done all at once, so time stays the same no matter how many protocols there are."
[OK] Correct: Each protocol must be checked separately, so more protocols mean more checks and more time.
Understanding how protocol composition affects performance helps you write clear and efficient Swift code, a skill that shows you know how to think about code behavior beyond just making it work.
"What if the protocols in the composition had inheritance relationships? How would that affect the time complexity of checking conformance?"