0
0
Swiftprogramming~20 mins

Sorted and custom comparators in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Sorting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Swift sorting code?

Consider the following Swift code that sorts an array of strings by their length in ascending order. What will be printed?

Swift
let words = ["apple", "banana", "fig", "date"]
let sortedWords = words.sorted { $0.count < $1.count }
print(sortedWords)
A["apple", "banana", "date", "fig"]
B["banana", "apple", "date", "fig"]
C["fig", "date", "apple", "banana"]
D["fig", "apple", "date", "banana"]
Attempts:
2 left
💡 Hint

Think about sorting by the number of letters in each word.

🧠 Conceptual
intermediate
1:30remaining
Which option correctly sorts integers descending using a custom comparator?

In Swift, you want to sort an array of integers from largest to smallest. Which sorting call correctly achieves this?

Anumbers.sorted(by: >)
Bnumbers.sorted(by: <)
Cnumbers.sorted { $0 < $1 }
Dnumbers.sorted { $0 == $1 }
Attempts:
2 left
💡 Hint

Think about the comparison operator that returns true when the first number is bigger.

🔧 Debug
advanced
2:00remaining
What error does this Swift sorting code produce?

Examine this Swift code snippet. What error will it cause when compiled?

Swift
let names = ["Anna", "Bob", "Charlie"]
let sortedNames = names.sorted { $0 > }
print(sortedNames)
ASyntaxError: Missing second operand in closure
BTypeError: Cannot compare String and Int
CRuntimeError: Index out of range
DNo error, prints ["Charlie", "Bob", "Anna"]
Attempts:
2 left
💡 Hint

Look carefully at the closure syntax inside the sorted method.

Predict Output
advanced
2:00remaining
What is the output of this Swift code sorting tuples by second element?

Given the array of tuples, what will be printed after sorting by the second element ascending?

Swift
let pairs = [("a", 3), ("b", 1), ("c", 2)]
let sortedPairs = pairs.sorted { $0.1 < $1.1 }
print(sortedPairs)
A[("c", 2), ("b", 1), ("a", 3)]
B[("b", 1), ("c", 2), ("a", 3)]
C[("b", 1), ("a", 3), ("c", 2)]
D[("a", 3), ("c", 2), ("b", 1)]
Attempts:
2 left
💡 Hint

Focus on sorting by the second value in each tuple.

🚀 Application
expert
2:30remaining
How many items are in the resulting array after this custom sort and filter?

Consider this Swift code that filters and sorts an array of integers. How many items remain after running it?

Swift
let numbers = [5, 3, 8, 1, 9, 2]
let filteredSorted = numbers.filter { $0 % 2 == 0 }.sorted(by: >)
print(filteredSorted.count)
A5
B3
C4
D2
Attempts:
2 left
💡 Hint

First find even numbers, then count how many remain after sorting.