Shorthand argument names ($0, $1) in Swift - Time & Space Complexity
We want to see how using shorthand argument names affects the speed of code.
Does using $0, $1 change how long the code takes to run as input grows?
Analyze the time complexity of the following code snippet.
let numbers = [1, 2, 3, 4, 5]
let doubled = numbers.map { $0 * 2 }
This code doubles each number in the list using shorthand argument $0 inside a map.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The map function loops over each element in the array.
- How many times: Once for every item in the array.
As the list gets bigger, the code runs more times, once per item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times the doubling operation |
| 100 | 100 times the doubling operation |
| 1000 | 1000 times the doubling operation |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the list gets bigger.
[X] Wrong: "Using $0 makes the code run faster or slower than naming the argument."
[OK] Correct: The shorthand $0 is just a shortcut for naming the argument. It does not change how many times the code runs or how long each step takes.
Understanding how shorthand arguments work helps you write clean code without worrying about slowing it down. This skill shows you know both style and performance basics.
"What if we replaced map with a nested loop using $0 and $1? How would the time complexity change?"