0
0
Swiftprogramming~5 mins

Default parameter values in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Default parameter values
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

Each time you increase the input number, the loop runs more times, printing more messages.

Input Size (times)Approx. Operations (prints)
1010
100100
10001000

Pattern observation: The number of prints grows directly with the input number.

Final Time Complexity

Time Complexity: O(n)

This means the time it takes grows in a straight line with the input number.

Common Mistake

[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.

Interview Connect

Understanding how default parameters work helps you explain function behavior clearly and shows you can think about how code runs as inputs change.

Self-Check

"What if the function called itself recursively instead of using a loop? How would the time complexity change?"