0
0
Swiftprogramming~10 mins

Shorthand argument names ($0, $1) in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A2
B1
C0
Dindex
Attempts:
3 left
💡 Hint
Common Mistakes
Using $1 when there is only one argument.
Using variable names instead of shorthand arguments.
2fill in blank
medium

Complete 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'
A0
B1
Cindex
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Using $1 when only one argument is passed.
Using variable names instead of shorthand arguments.
3fill in blank
hard

Fix 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'
A$0, $1
B0, 1
C1, 2
D$1, $0
Attempts:
3 left
💡 Hint
Common Mistakes
Using numeric literals instead of shorthand arguments.
Swapping $0 and $1 incorrectly.
4fill in blank
hard

Fill 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'
A$0
B$1
C0
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using numeric literals instead of shorthand arguments.
Using the same shorthand argument for both blanks.
5fill in blank
hard

Fill 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'
A$0
B$1
Attempts:
3 left
💡 Hint
Common Mistakes
Using $1 when only one argument is passed.
Mixing up tuple element indices.