Challenge - 5 Problems
Shorthand Argument Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Remember $0 refers to the first argument in the closure.
✗ Incorrect
The map function applies the closure to each element. $0 is each element, so multiplying by 2 doubles each number.
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Check the length of each word and how the closure compares them.
✗ Incorrect
The closure compares the length of two words using $0 and $1. It sorts words by length ascending. Since "banana" and "cherry" have equal lengths, Swift's stable sorting preserves their relative order from the original array.
🔧 Debug
advanced2: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)
Attempts:
2 left
💡 Hint
map closure receives one argument which is a tuple, not two separate arguments.
✗ Incorrect
The map closure receives each tuple as a single argument ($0). There is no $1 because the closure has only one parameter.
❓ Predict Output
advanced2: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)
Attempts:
2 left
💡 Hint
reduce starts with initial value 0 and adds each element using $0 and $1.
✗ Incorrect
reduce accumulates the sum starting from 0. $0 is the running total, $1 is the current element.
🧠 Conceptual
expert3: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)
Attempts:
2 left
💡 Hint
The inner closure uses $0 for elements inside each subarray, the outer closure uses $0 for each subarray.
✗ Incorrect
The outer flatMap takes each subarray ($0) and maps its elements multiplying by 2. flatMap then flattens the result into a single array.