0
0
Swiftprogramming~20 mins

Shorthand argument names ($0, $1) in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Shorthand Argument Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of map using shorthand argument names
What is the output of this Swift code using shorthand argument names?
Swift
let numbers = [1, 2, 3]
let doubled = numbers.map { $0 * 2 }
print(doubled)
A[0, 2, 4]
B[2, 4, 6]
C[1, 2, 3]
DCompilation error
Attempts:
2 left
💡 Hint
Remember $0 refers to the first argument in the closure.
Predict Output
intermediate
2:00remaining
Using $0 and $1 in sorted(by:)
What does this Swift code print?
Swift
let words = ["apple", "banana", "cherry"]
let sortedWords = words.sorted { $0.count < $1.count }
print(sortedWords)
A["apple", "cherry", "banana"]
B["apple", "banana", "cherry"]
C["banana", "apple", "cherry"]
DRuntime error
Attempts:
2 left
💡 Hint
Check the length of each word and how the closure compares them.
🔧 Debug
advanced
2:00remaining
Identify the error with shorthand argument names
Why does this Swift code cause a compilation error?
Swift
let pairs = [(1, 2), (3, 4)]
let sums = pairs.map { $0 + $1 }
print(sums)
ACannot use $1 because map closure takes only one argument
BCannot add tuples directly
CMissing return keyword in closure
DPairs array is empty
Attempts:
2 left
💡 Hint
map closure receives one argument which is a tuple, not two separate arguments.
Predict Output
advanced
2:00remaining
Output of reduce with shorthand arguments
What is the output of this Swift code?
Swift
let numbers = [1, 2, 3, 4]
let result = numbers.reduce(0) { $0 + $1 }
print(result)
A1
B24
C10
DCompilation error
Attempts:
2 left
💡 Hint
reduce starts with initial value 0 and adds each element using $0 and $1.
🧠 Conceptual
expert
3:00remaining
Understanding shorthand argument names in nested closures
Consider this Swift code snippet. What is the output printed?
Swift
let array = [[1, 2], [3, 4]]
let flattened = array.flatMap { $0.map { $0 * 2 } }
print(flattened)
A[1, 2, 3, 4]
B[[2, 4], [6, 8]]
CCompilation error due to ambiguous $0
D[2, 4, 6, 8]
Attempts:
2 left
💡 Hint
The inner closure uses $0 for elements inside each subarray, the outer closure uses $0 for each subarray.