0
0
Swiftprogramming~5 mins

Generic function declaration in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Generic function declaration
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run a generic function changes as the input size grows.

Specifically, we ask: how does the function's work increase when we give it more data?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func printElements(items: [T]) {
    for item in items {
        print(item)
    }
}

let numbers = [1, 2, 3, 4, 5]
printElements(items: numbers)
    

This function takes an array of any type and prints each element one by one.

Identify Repeating Operations
  • Primary operation: Looping through each element in the array.
  • How many times: Once for every item in the input array.
How Execution Grows With Input

As the number of items grows, the function prints more elements, so it takes more time.

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; doubling items doubles 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.

Common Mistake

[X] Wrong: "Generic functions are slower because they handle many types."

[OK] Correct: The generic part only affects type flexibility, not how many times the loop runs. The time depends on input size, not type.

Interview Connect

Understanding how generic functions scale helps you explain your code's efficiency clearly and confidently in real situations.

Self-Check

"What if we changed the function to print pairs of items instead of single items? How would the time complexity change?"