Functions as types in Swift - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: Calling the function
ftwice. - How many times: Exactly two times, no loops or recursion.
Each time we call applyTwice, the function f runs two times regardless of the input number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 2 calls to f |
| 100 | 2 calls to f |
| 1000 | 2 calls to f |
Pattern observation: The number of calls stays the same no matter how big the input number is.
Time Complexity: O(1)
This means the time to run does not grow with the input size; it stays constant.
[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.
Understanding how function calls affect time helps you explain code efficiency clearly and confidently.
What if we changed applyTwice to call the function f n times instead of two? How would the time complexity change?