Consider the following Swift code that sorts an array of strings by their length in ascending order. What will be printed?
let words = ["apple", "banana", "fig", "date"] let sortedWords = words.sorted { $0.count < $1.count } print(sortedWords)
Think about sorting by the number of letters in each word.
The code sorts the array by the length of each string from shortest to longest. "fig" has 3 letters, "date" 4, "apple" 5, and "banana" 6, so the sorted array is ["fig", "date", "apple", "banana"].
In Swift, you want to sort an array of integers from largest to smallest. Which sorting call correctly achieves this?
Think about the comparison operator that returns true when the first number is bigger.
Using the greater-than operator (>) sorts the array descending. The less-than operator (<) sorts ascending. The closure with equality (==) does not define a strict order and will not sort properly.
Examine this Swift code snippet. What error will it cause when compiled?
let names = ["Anna", "Bob", "Charlie"] let sortedNames = names.sorted { $0 > } print(sortedNames)
Look carefully at the closure syntax inside the sorted method.
The closure { $0 > } is incomplete because it lacks the second operand to compare with $0. This causes a syntax error.
Given the array of tuples, what will be printed after sorting by the second element ascending?
let pairs = [("a", 3), ("b", 1), ("c", 2)] let sortedPairs = pairs.sorted { $0.1 < $1.1 } print(sortedPairs)
Focus on sorting by the second value in each tuple.
The sorting closure compares the second element of each tuple. The order by second element ascending is 1, 2, then 3, so the sorted array is [("b", 1), ("c", 2), ("a", 3)].
Consider this Swift code that filters and sorts an array of integers. How many items remain after running it?
let numbers = [5, 3, 8, 1, 9, 2] let filteredSorted = numbers.filter { $0 % 2 == 0 }.sorted(by: >) print(filteredSorted.count)
First find even numbers, then count how many remain after sorting.
The filter keeps only even numbers from [5, 3, 8, 1, 9, 2]: 8 and 2. After sorting descending: [8, 2]. The count is 2.