Why extensions add capability without modifying in Swift - Performance Analysis
When we add new features to existing code using extensions, it's important to know how this affects the program's speed.
We want to see how the time to run the program changes as we add more work through extensions.
Analyze the time complexity of the following code snippet.
struct NumberList {
var numbers: [Int]
}
extension NumberList {
func sum() -> Int {
var total = 0
for num in numbers {
total += num
}
return total
}
}
This code adds a new function sum() to an existing structure without changing its original code.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the
numbersarray to add each number. - How many times: Once for each item in the array.
As the list of numbers grows, the time to add them all grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to run the sum() function grows in a straight line with the size of the list.
[X] Wrong: "Adding a function with an extension makes the program slower overall because it changes the original code."
[OK] Correct: Extensions add new features without changing existing code, so they don't slow down what was already there. The time depends on what the new function does, not on the extension itself.
Understanding how extensions add work helps you explain how your code grows and stays efficient. It shows you can add features smartly without breaking or slowing down existing parts.
"What if the sum() function used recursion instead of a loop? How would the time complexity change?"
Practice
Solution
Step 1: Understand what extensions do
Extensions add new methods or properties to existing types without altering the original source code.Step 2: Recognize the benefit
This allows adding features safely without changing or breaking existing code.Final Answer:
Because they add new features without changing existing code -> Option BQuick Check:
Extensions add features without modification = D [OK]
- Thinking extensions replace original types
- Believing extensions delete old methods
- Confusing extensions with subclassing
Solution
Step 1: Recall Swift extension syntax
Extensions start with the keyword 'extension' followed by the type name and braces enclosing new members.Step 2: Check each option
extension MyType { func newMethod() { } } matches the correct syntax: 'extension MyType { func newMethod() { } }'. Others have syntax errors.Final Answer:
extension MyType { func newMethod() { } } -> Option AQuick Check:
Correct extension syntax = A [OK]
- Using 'extend' instead of 'extension'
- Adding colon after type name
- Omitting braces around methods
struct Person { var name: String }
extension Person {
func greet() -> String {
return "Hello, \(name)!"
}
}
let p = Person(name: "Anna")
print(p.greet())Solution
Step 1: Understand the extension adds greet() method
The extension adds a greet() method to Person that returns "Hello, \(name)!" using the instance's name.Step 2: Check the instance and method call
Creating Person(name: "Anna") and calling greet() returns "Hello, Anna!".Final Answer:
Hello, Anna! -> Option AQuick Check:
Extension method works, output = Hello, Anna! [OK]
- Assuming extension methods can't access properties
- Expecting compile error for extension method
- Confusing string interpolation syntax
extension Int {
func squared() -> Int {
return self * self
}
}
let result = 5.squared
print(result)Solution
Step 1: Check method call syntax
The method squared() is defined correctly, but calling 5.squared misses parentheses.Step 2: Understand method call requirements
In Swift, methods must be called with parentheses even if no parameters, so 5.squared() is correct.Final Answer:
Missing parentheses when calling squared() -> Option DQuick Check:
Method call needs () = B [OK]
- Calling methods without parentheses
- Thinking Int cannot be extended
- Believing self is disallowed in extensions
isEven to Int using an extension that returns true if the number is even. Which code correctly achieves this without modifying the original Int type?Solution
Step 1: Understand computed property syntax
Computed properties use 'var name: Type { expression }' without parentheses.Step 2: Check each option
extension Int { var isEven: Bool { self % 2 == 0 } } correctly defines a computed property isEven returning true if self % 2 == 0. extension Int { func isEven() -> Bool { self % 2 == 0 } } uses a method, not a property. extension Int { static var isEven: Bool { self % 2 == 0 } } incorrectly uses static. extension Int { var isEven: Bool { return self / 2 == 0 } } uses wrong logic (division instead of modulo).Final Answer:
extension Int { var isEven: Bool { self % 2 == 0 } } -> Option CQuick Check:
Computed property with modulo check = A [OK]
- Using func instead of var for computed property
- Making property static when it should be instance
- Using division instead of modulo for even check
Ready to prove it?
Pass the test and this pattern moves unknown
