Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to sort the array in ascending order.
Swift
let numbers = [5, 3, 8, 1] let sortedNumbers = numbers.[1]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'sort()' which sorts the array in place and returns void.
Using 'reversed()' which reverses the array order.
Using 'map()' which transforms elements but does not sort.
✗ Incorrect
The 'sorted()' method returns a new array sorted in ascending order.
2fill in blank
mediumComplete the code to sort the array in descending order using a closure.
Swift
let numbers = [5, 3, 8, 1] let sortedNumbers = numbers.sorted(by: { $0 [1] $1 })
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' which sorts ascending.
Using '==' which does not sort properly.
Using '<=' which sorts ascending with duplicates.
✗ Incorrect
Using '>' in the closure sorts the array in descending order.
3fill in blank
hardFix the error in the code to sort an array of strings by their length.
Swift
let words = ["apple", "banana", "fig", "date"] let sortedWords = words.sorted(by: { $0.[1] < $1.count })
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'length' which is not a Swift String property.
Using 'size' which does not exist for strings.
Using 'length()' which is not a valid method.
✗ Incorrect
Strings in Swift use 'count' property to get their length.
4fill in blank
hardFill both blanks to create a dictionary of words and their lengths, including only words longer than 4 characters.
Swift
let words = ["apple", "banana", "fig", "date"] let wordLengths = Dictionary(uniqueKeysWithValues: words.filter { $0.count [2] 4 }.map { word in (word, [1]) })
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'count' alone without 'word.' prefix.
Using '<' instead of '>' for filtering.
Using 'length' which is not a Swift property.
✗ Incorrect
Use 'word.count' to get length and '>' to filter words longer than 4.
5fill in blank
hardFill all three blanks to create a sorted array of tuples (word, length) for words with length at least 5, sorted by length descending.
Swift
let words = ["apple", "banana", "fig", "date"] let filteredSorted = words.filter { $0.count [1] 5 }.map { [2] in ([2], [2].count) }.sorted { $0.1 [3] $1.1 }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>=' for filtering.
Using 'word' instead of 'w' for the map variable.
Using '<' in sorted closure which sorts ascending.
✗ Incorrect
Filter words with length >= 5, map to tuples (w, w.count), and sort descending by length using '>' operator.