0
0
Swiftprogramming~5 mins

Protocol declaration syntax in Swift - Time & Space Complexity

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

Let's see how the time to declare a protocol changes as the protocol grows.

We want to know how adding more requirements affects the work done when declaring a protocol.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


protocol Vehicle {
    var numberOfWheels: Int { get }
    func startEngine()
    func stopEngine()
    func drive(distance: Double)
}

This code declares a protocol named Vehicle with some properties and methods that any conforming type must implement.

Identify Repeating Operations

Look for parts that repeat or grow with input size.

  • Primary operation: Listing each property and method requirement inside the protocol.
  • How many times: Once for each requirement added to the protocol.
How Execution Grows With Input

As you add more requirements, the work to declare the protocol grows in a simple way.

Input Size (n)Approx. Operations
44 operations (4 requirements)
1010 operations
100100 operations

Pattern observation: The work grows directly with the number of requirements you add.

Final Time Complexity

Time Complexity: O(n)

This means the time to declare a protocol grows linearly with the number of requirements it has.

Common Mistake

[X] Wrong: "Declaring a protocol always takes the same time no matter how many requirements it has."

[OK] Correct: Each requirement adds a small amount of work, so more requirements mean more time to declare.

Interview Connect

Understanding how code size affects work helps you write efficient and clear protocols, a skill useful in real projects and interviews.

Self-Check

"What if the protocol inherits from multiple other protocols? How would the time complexity change?"