0
0
Swiftprogramming~5 mins

Extension syntax in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Extension syntax
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: A loop that goes through each item in the array.
  • How many times: Once for every item in the array.
How Execution Grows With Input

As the array gets bigger, the function prints more items, so it does more work.

Input Size (n)Approx. Operations
1010 print actions
100100 print actions
10001000 print actions

Pattern observation: The work grows directly with the number of items; double the items, double the work.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Knowing how extensions affect time helps you explain your code clearly and shows you understand how your program grows with input size.

Self-Check

"What if the extension function called another function that itself loops over the array? How would the time complexity change?"