0
0
Swiftprogramming~5 mins

Protocol composition in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Protocol composition
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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).
How Execution Grows With Input

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
33
1010
100100

Pattern observation: The time to check grows in a straight line as you add more protocols.

Final Time Complexity

Time Complexity: O(n)

This means the time to check protocol composition grows proportionally with the number of protocols combined.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if the protocols in the composition had inheritance relationships? How would that affect the time complexity of checking conformance?"