0
0
Swiftprogramming~10 mins

Sorted and custom comparators 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 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'
Amap
Bsorted
Creversed
Dsort
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.
2fill in blank
medium

Complete 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'
A>
B<
C==
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' which sorts ascending.
Using '==' which does not sort properly.
Using '<=' which sorts ascending with duplicates.
3fill in blank
hard

Fix 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'
Asize
Blength()
Ccount
Dlength
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.
4fill in blank
hard

Fill 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'
Aword.count
Bcount
C>
Dlength
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.
5fill in blank
hard

Fill 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'
A>=
Bword
Cw
D>
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.