0
0
Swiftprogramming~5 mins

Protocol requirements (methods and properties) in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Protocol requirements (methods and properties)
O(n)
Understanding Time Complexity

When using protocols with required methods and properties, it's important to know how the time to run code changes as the program grows.

We want to see how the number of operations grows when calling these protocol requirements.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


protocol Drawable {
    func draw()
    var color: String { get }
}

func renderAll(drawables: [Drawable]) {
    for item in drawables {
        item.draw()
        print(item.color)
    }
}
    

This code defines a protocol with a method and a property, then calls them on each item in a list.

Identify Repeating Operations

Look for loops or repeated calls.

  • Primary operation: Looping through the array and calling draw() and accessing color on each item.
  • How many times: Once for each item in the drawables array.
How Execution Grows With Input

As the number of items grows, the number of calls grows the same way.

Input Size (n)Approx. Operations
10About 10 calls to draw() and 10 property accesses
100About 100 calls to draw() and 100 property accesses
1000About 1000 calls to draw() and 1000 property accesses

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items.

Common Mistake

[X] Wrong: "Calling protocol methods is slower and adds extra loops behind the scenes."

[OK] Correct: Calling a protocol method or property is just like calling any method once per item; it does not add hidden loops or extra repeated work.

Interview Connect

Understanding how protocol requirements affect performance helps you explain your code choices clearly and confidently in real projects.

Self-Check

What if the draw() method itself contained a loop over another collection? How would that change the time complexity?