Recall & Review
beginner
What does the
sorted() method do in Swift?The
sorted() method returns a new array with the elements sorted in ascending order by default.Click to reveal answer
beginner
How do you use a custom comparator with
sorted(by:) in Swift?You provide a closure that takes two elements and returns
true if the first element should be ordered before the second, otherwise false.Click to reveal answer
beginner
Example: Sort an array of integers in descending order using
sorted(by:).Use <code>let sortedArray = array.sorted(by: { $0 > $1 })</code> to sort from highest to lowest.Click to reveal answer
intermediate
Why use a custom comparator instead of the default
sorted()?A custom comparator lets you define your own sorting rules, like sorting strings by length or sorting objects by a property.
Click to reveal answer
intermediate
What is the type signature of the closure used in
sorted(by:)?The closure has type
(Element, Element) -> Bool, where it compares two elements and returns true if the first should come before the second.Click to reveal answer
What does
array.sorted() return in Swift?✗ Incorrect
sorted() returns a new sorted array and does not change the original.
Which closure signature is correct for
sorted(by:)?✗ Incorrect
The closure compares two elements and returns true if the first should come before the second.
How do you sort an array of strings by their length in ascending order?
✗ Incorrect
Use a custom comparator comparing the count property to sort by length.
What happens if you use
sorted(by: { $0 < $1 })?✗ Incorrect
This comparator sorts elements from smallest to largest (ascending).
Can
sorted(by:) be used to sort arrays of custom objects?✗ Incorrect
You can sort custom objects by defining how to compare them in the closure.
Explain how to sort an array in Swift using a custom comparator.
Think about how you tell Swift the order you want.
You got /4 concepts.
Describe the difference between
sorted() and sorted(by:).One is simple, the other lets you decide the order.
You got /3 concepts.