0
0
Swiftprogramming~10 mins

Why collection algorithms matter in Swift - Test Your Understanding

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

Complete the code to find the first element in the array.

Swift
let numbers = [1, 2, 3, 4, 5]
let firstNumber = numbers.[1]
Drag options to blanks, or click blank then click option'
Alast()
Bfirst()
Ccount
Dappend()
Attempts:
3 left
💡 Hint
Common Mistakes
Using last() returns the last element, not the first.
Using count returns the number of elements, not an element.
append() adds an element, it does not retrieve one.
2fill in blank
medium

Complete the code to filter numbers greater than 3.

Swift
let numbers = [1, 2, 3, 4, 5]
let filtered = numbers.filter { $0 [1] 3 }
Drag options to blanks, or click blank then click option'
A>
B<
C==
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' filters numbers less than 3, not greater.
Using '==' filters only numbers equal to 3.
Using '<=' includes numbers less than or equal to 3.
3fill in blank
hard

Fix the error in the code to sum all numbers in the array.

Swift
let numbers = [1, 2, 3, 4, 5]
let total = numbers.reduce(0, [1])
Drag options to blanks, or click blank then click option'
A{ $1 * $0 }
B{ $0 / $1 }
C{ $0 - $1 }
D{ $0 + $1 }
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication changes the result.
Division can cause runtime errors if dividing by zero.
4fill in blank
hard

Fill both blanks to create a dictionary of word lengths for words longer than 3 characters.

Swift
let words = ["apple", "bat", "car", "door"]
let lengths = [String: Int](uniqueKeysWithValues: words.filter { $0.count [1] 3 }.map { ($0, $0.[2]) })
Drag options to blanks, or click blank then click option'
A>
Bcount
Clength
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' filters shorter words, not longer.
Using 'length' is not a valid property in Swift strings.
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase keys and values greater than 2.

Swift
let data = ["one": 1, "two": 2, "three": 3]
let result = data.filter { $0.value [1] 2 }.mapKeys { $0.key.[2]() }.mapValues { $0.[3] }
Drag options to blanks, or click blank then click option'
A>
Buppercased
Cdescription
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' filters values less than 2.
Using 'lowercased' converts keys to lowercase, not uppercase.
Using 'count' on values is invalid since values are Int.