Protocol extensions for shared behavior in Swift - Time & Space Complexity
We want to understand how adding shared behavior through protocol extensions affects the time it takes for code to run.
Specifically, how does the number of operations grow when using protocol extensions in Swift?
Analyze the time complexity of the following code snippet.
protocol Greetable {
func greet()
}
extension Greetable {
func greet() {
print("Hello from protocol extension!")
}
}
struct Person: Greetable {}
let people = Array(repeating: Person(), count: n)
for person in people {
person.greet()
}
This code defines a protocol with a default greeting method, creates many Person instances conforming to it, and calls greet on each.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling
greet()on each element in the array. - How many times: Exactly
ntimes, once per element.
Each additional person adds one more call to greet(). So the total work grows directly with the number of people.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 greet calls |
| 100 | 100 greet calls |
| 1000 | 1000 greet calls |
Pattern observation: The work grows in a straight line as the input size increases.
Time Complexity: O(n)
This means the time to run grows directly in proportion to how many items we have.
[X] Wrong: "Using protocol extensions makes the code run slower because it adds extra layers."
[OK] Correct: Protocol extensions provide shared behavior without adding extra loops or nested calls; the main cost is still just calling the method once per item.
Understanding how protocol extensions affect performance shows you can write clean code without worrying about hidden slowdowns, a skill valuable in real projects and interviews.
"What if the greet() method inside the protocol extension called another method that loops over a collection? How would the time complexity change?"
Practice
protocol extensions in Swift?Solution
Step 1: Understand protocol extensions
Protocol extensions allow adding default method or property implementations to protocols.Step 2: Identify the benefit
This lets many types share behavior without rewriting the same code.Final Answer:
To add shared behavior to multiple types without repeating code -> Option BQuick Check:
Protocol extensions = shared behavior [OK]
- Thinking protocols can store data
- Confusing protocol extensions with inheritance
- Believing protocol extensions prevent conformance
greet() to a protocol Greeter using an extension?Solution
Step 1: Recall protocol extension syntax
To add default behavior, useextension ProtocolName { func method() { ... } }.Step 2: Check each option
extension Greeter { func greet() { print("Hello") } } correctly usesextension Greeter { func greet() { ... } }. Others misuse protocol or extension syntax.Final Answer:
extension Greeter { func greet() { print("Hello") } } -> Option CQuick Check:
Extension syntax = extension ProtocolName { func ... } [OK]
- Putting method inside protocol body with implementation
- Using 'extension' keyword inside protocol declaration
- Trying to add method with colon syntax
protocol Vehicle {
func start()
}
extension Vehicle {
func start() {
print("Starting vehicle")
}
}
struct Car: Vehicle {}
let myCar = Car()
myCar.start()What will be printed when this code runs?
Solution
Step 1: Understand protocol and extension
The protocol Vehicle requires a start() method. The extension provides a default implementation.Step 2: Check struct Car conformance
Car conforms to Vehicle but does not implement start(), so it uses the default from the extension.Final Answer:
Starting vehicle -> Option AQuick Check:
Default method runs if not overridden [OK]
- Expecting compile error for missing method
- Thinking no output will print
- Confusing runtime error with missing implementation
protocol Speaker {
func speak()
}
extension Speaker {
func speak() {
print("Speaking")
}
}
struct Person: Speaker {
func speak() {
print("Hello")
}
}
let p = Person()
p.speak()What is the error and how to fix it?
Solution
Step 1: Analyze protocol and extension
Protocol Speaker requires speak(). Extension provides default implementation.Step 2: Check struct Person implementation
Person implements speak(), overriding the default. This is allowed and correct.Final Answer:
No error; output is 'Hello' -> Option AQuick Check:
Override default method by implementing in type [OK]
- Thinking default methods cause errors
- Trying to use 'override' keyword in struct
- Believing protocol methods must be optional
describe() to multiple unrelated types Cat and Dog without repeating code. Which approach using protocol extensions is best?Solution
Step 1: Identify shared behavior need
Both Cat and Dog need the same describe() method without repeating code.Step 2: Use protocol with extension
Define protocol Animal with describe(), then provide default describe() in protocol extension. Make Cat and Dog conform to Animal.Final Answer:
Create a protocol Animal with describe() and add default implementation in extension; make Cat and Dog conform -> Option DQuick Check:
Protocol extension = shared behavior for unrelated types [OK]
- Repeating code in each type
- Using class inheritance when types are unrelated
- Using global functions losing type safety
Ready to prove it?
Pass the test and this pattern moves unknown
