Default parameter values in Swift - Time & Space Complexity
We want to see how using default values for function parameters affects how long the code takes to run.
Does adding default values change how the program grows with bigger inputs?
Analyze the time complexity of the following code snippet.
func greet(times: Int = 1) {
for _ in 1...times {
print("Hello!")
}
}
greet(times: 3)
This function prints "Hello!" a number of times, using a default value if no number is given.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that prints "Hello!" multiple times.
- How many times: It runs exactly as many times as the input number (times).
Each time you increase the input number, the loop runs more times, printing more messages.
| Input Size (times) | Approx. Operations (prints) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of prints grows directly with the input number.
Time Complexity: O(n)
This means the time it takes grows in a straight line with the input number.
[X] Wrong: "Using default values makes the function faster or slower depending on the default."
[OK] Correct: The default value only sets what happens if no input is given; it does not change how many times the loop runs when a number is provided.
Understanding how default parameters work helps you explain function behavior clearly and shows you can think about how code runs as inputs change.
"What if the function called itself recursively instead of using a loop? How would the time complexity change?"