Extension syntax in Swift - Time & Space Complexity
When we add new features to existing code using extensions, it's important to know how this affects the time it takes to run our program.
We want to understand how the extra code inside an extension changes the work the program does as input grows.
Analyze the time complexity of the following code snippet.
extension Array {
func printAll() {
for item in self {
print(item)
}
}
}
let numbers = [1, 2, 3, 4, 5]
numbers.printAll()
This code adds a new function to all arrays that prints each item one by one.
- Primary operation: A loop that goes through each item in the array.
- How many times: Once for every item in the array.
As the array gets bigger, the function prints more items, so it does more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print actions |
| 100 | 100 print actions |
| 1000 | 1000 print actions |
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 function grows in a straight line with the number of items in the array.
[X] Wrong: "Adding an extension always makes the program slower in a big way."
[OK] Correct: Extensions just add code like any other function; the time depends on what the code does, not that it is in an extension.
Knowing how extensions affect time helps you explain your code clearly and shows you understand how your program grows with input size.
"What if the extension function called another function that itself loops over the array? How would the time complexity change?"
Practice
extension in Swift?Solution
Step 1: Understand what extensions do
Extensions allow adding new features to existing types without changing their original source code.Step 2: Compare options with this definition
Only adding new functionality to an existing type without modifying its original code correctly describes this purpose. Replacing original implementation refers to overriding, creating subclasses is inheritance, and deleting methods is unrelated to extensions.Final Answer:
To add new functionality to an existing type without modifying its original code -> Option AQuick Check:
Extension purpose = Add features without changing original code [OK]
- Confusing extensions with subclassing
- Thinking extensions replace original code
- Believing extensions can remove methods
String type in Swift?Solution
Step 1: Recall Swift extension syntax
The correct syntax starts with the keywordextensionfollowed by the type name without parentheses or brackets.Step 2: Check each option
extension String { }uses correct syntax.extend String { }uses invalid keyword.extension String() { }adds invalid parentheses.extension String[] { }uses invalid array notation.Final Answer:
extension String { } -> Option BQuick Check:
Extension syntax = extension TypeName { } [OK]
- Using 'extend' instead of 'extension'
- Adding parentheses after type name
- Using brackets after type name
extension Int {
func squared() -> Int {
return self * self
}
}
let number = 4
print(number.squared())Solution
Step 1: Understand the extension method
The extension adds a methodsquared()to Int that returns the number multiplied by itself.Step 2: Calculate the output for number = 4
Calling4.squared()returns 4 * 4 = 16.Final Answer:
16 -> Option AQuick Check:
4 squared = 16 [OK]
- Confusing squared with doubling
- Expecting syntax error due to extension
- Forgetting to return the value
extension Double {
func half() -> Double {
self / 2
}
}Solution
Step 1: Check method syntax in extension
In Swift, single-expression functions can omit thereturnkeyword.Step 2: Verify if extension on Double is allowed
Extensions can add methods to Double. The method name 'half' is valid.Final Answer:
No error, code is correct -> Option DQuick Check:
Single-expression methods can omit return [OK]
- Assuming 'return' is always required
- Thinking extensions can't add methods to built-in types
- Believing method names have restrictions
isEven to Int using an extension that returns true if the number is even, otherwise false. Which code correctly implements this?Solution
Step 1: Understand computed property syntax
Computed properties usevarwith a getter.extension Int { var isEven: Bool { self % 2 == 0 } }uses correct concise syntax; the func version declares a method, the if version lacks an else branch causing compile error, the division version has wrong logic.Step 2: Check logic correctness
extension Int { var isEven: Bool { self % 2 == 0 } }uses concise expressionself % 2 == 0which returns true if even.extension Int { var isEven: Bool { if self % 2 == 0 { return true } } }omits else branch, causing compiler error.extension Int { var isEven: Bool { self / 2 == 0 } }incorrectly uses division instead of modulo.Step 3: Verify distractors
The method requires parentheses to call likenum.isEven(). Incomplete if fails to compile. Division fails for even numbers like 2 (2/2 == 1 != 0).Final Answer:
extension Int { var isEven: Bool { self % 2 == 0 } } -> Option CQuick Check:
Computed property with modulo check = extension Int { var isEven: Bool { self % 2 == 0 } } [OK]
- Using division instead of modulo
- Confusing method with computed property
- Forgetting to return a Bool value
Ready to prove it?
Pass the test and this pattern moves unknown
