0
0
Swiftprogramming~5 mins

Functions as types in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Functions as types
O(1)
Understanding Time Complexity

When we use functions as types, we want to know how calling these functions affects how long our program takes to run.

We ask: How does the time grow when we call functions stored as variables or passed around?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func applyTwice(_ f: (Int) -> Int, to x: Int) -> Int {
    return f(f(x))
}

func addOne(_ n: Int) -> Int {
    return n + 1
}

let result = applyTwice(addOne, to: 5)
print(result) // 7
    

This code calls a function passed as a parameter two times in a row on a number.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the function f twice.
  • How many times: Exactly two times, no loops or recursion.
How Execution Grows With Input

Each time we call applyTwice, the function f runs two times regardless of the input number.

Input Size (n)Approx. Operations
102 calls to f
1002 calls to f
10002 calls to f

Pattern observation: The number of calls stays the same no matter how big the input number is.

Final Time Complexity

Time Complexity: O(1)

This means the time to run does not grow with the input size; it stays constant.

Common Mistake

[X] Wrong: "Calling a function twice means the time doubles with input size."

[OK] Correct: The number of calls is fixed at two, so time does not grow with input size.

Interview Connect

Understanding how function calls affect time helps you explain code efficiency clearly and confidently.

Self-Check

What if we changed applyTwice to call the function f n times instead of two? How would the time complexity change?