Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to print the squares of numbers using shorthand argument names.
Swift
let numbers = [1, 2, 3, 4] let squares = numbers.map { $[1] * $[1] } print(squares)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using $1 when there is only one argument.
Using variable names instead of shorthand arguments.
✗ Incorrect
The shorthand argument $0 refers to the first argument passed to the closure, which is each element in the array.
2fill in blank
mediumComplete the code to filter numbers greater than 3 using shorthand argument names.
Swift
let numbers = [1, 2, 3, 4, 5] let filtered = numbers.filter { $[1] > 3 } print(filtered)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using $1 when only one argument is passed.
Using variable names instead of shorthand arguments.
✗ Incorrect
The closure passed to filter takes each element as the first argument, accessible via $0.
3fill in blank
hardFix the error in the code by using the correct shorthand argument name to sort pairs by their second value.
Swift
let pairs = [("a", 3), ("b", 1), ("c", 2)] let sorted = pairs.sorted { $[1].1 < $[2].1 } print(sorted)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using numeric literals instead of shorthand arguments.
Swapping $0 and $1 incorrectly.
✗ Incorrect
The closure for sorted takes two arguments, accessible as $0 and $1. We compare their second elements with .1.
4fill in blank
hardFill both blanks to create a closure that adds two numbers using shorthand argument names.
Swift
let add = { $[1] + $[2] }
print(add(5, 7)) Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using numeric literals instead of shorthand arguments.
Using the same shorthand argument for both blanks.
✗ Incorrect
The closure takes two arguments, accessible as $0 and $1, which we add together.
5fill in blank
hardFill all three blanks to create a dictionary from an array of tuples using shorthand argument names.
Swift
let items = [("apple", 3), ("banana", 5), ("cherry", 2)] let dict = Dictionary(uniqueKeysWithValues: items.map { ( $[1].0, $[2].1 ) }) print(dict)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using $1 when only one argument is passed.
Mixing up tuple element indices.
✗ Incorrect
The map closure takes one argument (a tuple), accessible as $0. We use $0.0 for the key and $0.1 for the value.