0
0
Swiftprogramming~5 mins

Sorted and custom comparators in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AThe original array sorted in place
BAn error if the array is not sorted
CA Boolean indicating if the array is sorted
DA new array sorted in ascending order
Which closure signature is correct for sorted(by:)?
A(Element, Element) -> Bool
B(Element) -> Bool
C(Element, Element) -> Element
D(Element) -> Element
How do you sort an array of strings by their length in ascending order?
Aarray.sorted()
Barray.sorted(by: { $0.count < $1.count })
Carray.sorted(by: { $0 > $1 })
Darray.sorted(by: { $0.count > $1.count })
What happens if you use sorted(by: { $0 < $1 })?
ACauses a runtime error
BSorts the array in descending order
CSorts the array in ascending order
DLeaves the array unsorted
Can sorted(by:) be used to sort arrays of custom objects?
AYes, by providing a closure comparing object properties
BNo, only basic types can be sorted
COnly if the objects conform to <code>Comparable</code>
DOnly if the array is mutable
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.