Protocol declaration syntax in Swift - Time & Space 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.
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.
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.
As you add more requirements, the work to declare the protocol grows in a simple way.
| Input Size (n) | Approx. Operations |
|---|---|
| 4 | 4 operations (4 requirements) |
| 10 | 10 operations |
| 100 | 100 operations |
Pattern observation: The work grows directly with the number of requirements you add.
Time Complexity: O(n)
This means the time to declare a protocol grows linearly with the number of requirements it has.
[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.
Understanding how code size affects work helps you write efficient and clear protocols, a skill useful in real projects and interviews.
"What if the protocol inherits from multiple other protocols? How would the time complexity change?"