0
0
Swiftprogramming~10 mins

Shorthand argument names ($0, $1) in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Shorthand argument names ($0, $1)
Start closure call
Use $0 for first argument
Use $1 for second argument
Perform operation with $0, $1
Return result
Closure ends
The closure starts, uses $0 and $1 as shorthand for its first and second arguments, performs operations, returns a result, and ends.
Execution Sample
Swift
let sum = { $0 + $1 }
let result = sum(3, 5)
print(result)
Defines a closure that adds two numbers using $0 and $1, then calls it with 3 and 5, printing the result.
Execution Table
StepActionEvaluationResult
1Define closure sumClosure expects two argumentsClosure stored in sum
2Call sum(3, 5)$0 = 3, $1 = 5Evaluate $0 + $1
3Calculate 3 + 53 + 58
4Print resultOutput result8
💡 Closure call completes and result 8 is printed
Variable Tracker
VariableStartAfter CallFinal
sumClosure (not called)Closure called with $0=3, $1=5Closure (unchanged)
resultundefined88
Key Moments - 2 Insights
Why do we use $0 and $1 instead of naming arguments?
Because the closure is short and Swift lets us use $0, $1 as quick names for the first and second arguments, as shown in execution_table step 2.
What happens if we use $2 in this closure?
There is no third argument, so using $2 would cause an error. The closure only has $0 and $1 as in execution_table step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of $1 when sum is called?
A3
B5
C8
Dundefined
💡 Hint
Check execution_table row 2 where $0=3 and $1=5
At which step is the closure result stored in variable 'result'?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at execution_table row 3 where calculation 3 + 5 equals 8
If we changed the closure to { $0 * $1 }, what would be printed?
A8
B35
C15
DError
💡 Hint
Multiply 3 * 5 as in variable_tracker after call values
Concept Snapshot
Shorthand argument names $0, $1 let you quickly access closure arguments without naming them.
Use $0 for the first argument, $1 for the second, and so on.
This is handy for short closures.
Example: let sum = { $0 + $1 } adds two numbers.
Call with sum(3, 5) returns 8.
Full Transcript
This visual trace shows how Swift shorthand argument names $0 and $1 work inside a closure. The closure sum is defined to add two numbers using $0 and $1 as quick argument names. When sum is called with 3 and 5, $0 becomes 3 and $1 becomes 5. The closure adds them to get 8, which is stored in result and printed. Beginners often wonder why $0 and $1 are used instead of named arguments; it's a shortcut for simple closures. Also, using $2 would cause an error because only two arguments exist. Changing the operation inside the closure changes the output accordingly.