Extending built-in types in Swift - Time & Space Complexity
When we add new features to built-in types in Swift, it's important to know how this affects the time it takes to run our code.
We want to find out how the time to run grows as the input size changes when using these extensions.
Analyze the time complexity of the following code snippet.
extension Array where Element == Int {
func doubledElements() -> [Int] {
var result = [Int]()
for item in self {
result.append(item * 2)
}
return result
}
}
let numbers = [1, 2, 3, 4, 5]
let doubled = numbers.doubledElements()
This code adds a new function to arrays of integers that creates a new array with each number doubled.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through each item in the array.
- How many times: It runs once for every element in the array.
As the array gets bigger, the function takes longer because it doubles each item one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times doubling |
| 100 | 100 times doubling |
| 1000 | 1000 times doubling |
Pattern observation: The time grows directly with the number of items; double the items means double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of elements in the array.
[X] Wrong: "Adding a function to a built-in type makes the code run instantly or slower regardless of input size."
[OK] Correct: The time depends on what the function does. If it processes each item, time grows with input size, not just because it is an extension.
Understanding how extending built-in types affects time helps you write clear and efficient code, a skill valued in many coding challenges and real projects.
"What if the extension function used recursion instead of a loop? How would the time complexity change?"
Practice
Solution
Step 1: Understand what extensions do
Extensions allow adding new methods or computed properties to existing types without subclassing.Step 2: Identify what extensions cannot do
Extensions cannot add stored properties or delete existing methods.Final Answer:
To add new methods or computed properties to existing types -> Option CQuick Check:
Extensions add methods/properties = B [OK]
- Thinking extensions can add stored properties
- Confusing extensions with subclassing
- Believing extensions can remove methods
Int type with a method isEven() that returns a Bool?Solution
Step 1: Identify the correct keyword for extension
Swift uses the keywordextensionto add methods to existing types.Step 2: Check method syntax
The method must have parentheses and a return type:func isEven() -> Bool. The body usesself % 2 == 0.Final Answer:
extension Int { func isEven() -> Bool { return self % 2 == 0 } } -> Option AQuick Check:
Correct extension syntax = D [OK]
- Using 'extend' instead of 'extension'
- Omitting parentheses in method declaration
- Missing 'func' keyword before method name
extension String {
func reversedString() -> String {
return String(self.reversed())
}
}
let word = "hello"
print(word.reversedString())What is the output when this code runs?
Solution
Step 1: Understand the extension method
The methodreversedString()returns a new String made by reversing the characters of the original string.Step 2: Apply method to 'hello'
Reversing "hello" results in "olleh".Final Answer:
olleh -> Option DQuick Check:
String reversed = olleh [OK]
- Expecting original string output
- Thinking reversed() returns an error
- Confusing reversed() with reverse()
extension Double {
var squared: Double {
return self * self
}
var storedValue: Double = 0.0
}Solution
Step 1: Review extension property rules
Extensions can add computed properties but cannot add stored properties.Step 2: Identify the stored property
The linevar storedValue: Double = 0.0tries to add a stored property, which is not allowed.Final Answer:
Extensions cannot add stored properties like 'storedValue' -> Option AQuick Check:
No stored properties in extensions = A [OK]
- Trying to add stored properties in extensions
- Confusing computed properties with stored properties
- Thinking extensions require 'class' keyword
Array type in Swift to add a method secondElement() that returns the second element if it exists, or nil otherwise. Which of the following extensions correctly implements this?Solution
Step 1: Check method signature and return type
The method should return an optional Element (Element?) because the second element might not exist.Step 2: Verify index and condition
Arrays are zero-indexed, so the second element is at index 1. The condition should check if count > 1 to safely access index 1.Step 3: Compare options
The correct one uses ternary operator:return self.count > 1 ? self[1] : nil. The non-optional return crashes on short arrays. The computed property uses index 2 (third element). The if-else checks count > 0, allowing index 1 access when count == 1, causing runtime crash.Final Answer:
extension Array { func secondElement() -> Element? { return self.count > 1 ? self[1] : nil } } -> Option BQuick Check:
Safe optional return with index 1 = A [OK]
- Accessing wrong index (like 2 instead of 1)
- Returning non-optional Element causing crash
- Using computed property but with wrong index
Ready to prove it?
Pass the test and this pattern moves unknown
