Variadic parameters in Swift - Time & Space Complexity
When using variadic parameters, we want to know how the time to run the function changes as we pass more values.
How does the function handle many inputs and how long does it take?
Analyze the time complexity of the following code snippet.
func sum(numbers: Int...) -> Int {
var total = 0
for number in numbers {
total += number
}
return total
}
This function adds up all the numbers passed to it using a variadic parameter.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the variadic parameter.
- How many times: Once for each number passed to the function.
As you add more numbers, the function does more additions, one for each number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of inputs.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of inputs.
[X] Wrong: "Variadic parameters make the function run instantly no matter how many inputs."
[OK] Correct: The function still processes each input one by one, so more inputs mean more work.
Understanding how variadic parameters affect time helps you explain how your code scales when handling many inputs.
"What if we changed the function to multiply the numbers instead of adding? How would the time complexity change?"