Bird
Raised Fist0
Swiftprogramming~10 mins

Sorted and custom comparators in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Sorted and custom comparators
Start with array
↓
Call sorted()
↓
Check if custom comparator provided?
No→Use default ascending order
Yes↓
Use custom comparator to compare elements
↓
Sort elements accordingly
↓
Return sorted array
↓
End
The array is sorted by calling sorted(). If a custom comparator is given, it compares elements using that; otherwise, it sorts in ascending order.
Execution Sample
Swift
let numbers = [3, 1, 4, 2]
let sortedAsc = numbers.sorted()
let sortedDesc = numbers.sorted { $0 > $1 }
Sorts an array ascending by default, then descending using a custom comparator.
Execution Table
StepActionComparator UsedComparison ExampleResulting Array
1Start with arrayN/AN/A[3, 1, 4, 2]
2Call sorted() without comparatorDefault ascendingCompare 3 and 1: 3 > 1[1, 2, 3, 4]
3Call sorted() with custom comparatorCustom: $0 > $1 (descending)Compare 3 and 1: 3 > 1 is true[4, 3, 2, 1]
4EndN/AN/ASorted arrays ready
💡 Sorting completes after comparing all elements using the chosen comparator.
Variable Tracker
VariableStartAfter sorted()After sorted { $0 > $1 }
numbers[3, 1, 4, 2][3, 1, 4, 2][3, 1, 4, 2]
sortedAscN/A[1, 2, 3, 4][1, 2, 3, 4]
sortedDescN/AN/A[4, 3, 2, 1]
Key Moments - 3 Insights
Why does sorted() without a comparator sort in ascending order?
By default, sorted() uses the natural order of elements (like numbers from smallest to largest), as shown in step 2 of the execution_table.
How does the custom comparator { $0 > $1 } change sorting?
It tells sorted() to put bigger numbers first by comparing if the first element is greater than the second, reversing the order (step 3).
Does the original array change after sorting?
No, sorted() returns a new sorted array and leaves the original array unchanged, as seen in variable_tracker where 'numbers' stays the same.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the array after calling sorted() without a comparator?
A[4, 3, 2, 1]
B[1, 2, 3, 4]
C[3, 1, 4, 2]
D[2, 3, 1, 4]
💡 Hint
Check step 2 in the execution_table under 'Resulting Array'.
At which step does the sorting use the custom comparator?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look for the step mentioning 'custom comparator' in the execution_table.
If the comparator was changed to { $0 < $1 }, how would the sorted array change?
AIt would sort descending
BIt would not sort
CIt would sort ascending
DIt would reverse the array
💡 Hint
The comparator { $0 < $1 } means smaller elements come first, like the default ascending order.
Concept Snapshot
sorted() returns a new sorted array.
By default, it sorts ascending.
Custom comparator closure defines order.
Comparator returns true if first element should come before second.
Original array stays unchanged.
Use sorted(by:) for custom sorting.
Full Transcript
This example shows how to sort arrays in Swift using sorted(). First, the array [3, 1, 4, 2] is sorted ascending by default, producing [1, 2, 3, 4]. Then, a custom comparator { $0 > $1 } is used to sort descending, producing [4, 3, 2, 1]. The original array remains unchanged. The flow starts with the array, calls sorted(), checks if a custom comparator is provided, uses it if yes, sorts accordingly, and returns the sorted array. Variables track the original and sorted arrays. Key points include default ascending order, how the comparator changes sorting, and that sorted() returns a new array without modifying the original.

Practice

(1/5)
1. What does the sorted(by:) method do in Swift?
easy
A. It sorts an array using a custom rule you provide.
B. It removes duplicate elements from an array.
C. It reverses the order of elements in an array.
D. It filters elements based on a condition.

Solution

  1. Step 1: Understand the purpose of sorted(by:)

    This method sorts elements of an array based on a closure that defines the order.
  2. Step 2: Compare with other array methods

    Unlike filtering or reversing, sorted(by:) changes order based on a custom rule.
  3. Final Answer:

    It sorts an array using a custom rule you provide. -> Option A
  4. Quick Check:

    sorted(by:) = custom sorting [OK]
Hint: Remember: sorted(by:) arranges items your way [OK]
Common Mistakes:
  • Confusing sorting with filtering
  • Thinking it removes duplicates
  • Assuming it reverses the array
2. Which of the following is the correct syntax to sort an array of integers in descending order using sorted(by:)?
easy
A. let sortedArray = numbers.sorted(by: { $1 > $0 })
B. let sortedArray = numbers.sorted(by: { $0 < $1 })
C. let sortedArray = numbers.sorted()
D. let sortedArray = numbers.sorted(by: { $0 > $1 })

Solution

  1. Step 1: Understand sorting order

    To sort descending, the comparator must return true when the first element is greater than the second.
  2. Step 2: Check each option

    let sortedArray = numbers.sorted(by: { $0 > $1 }) uses { $0 > $1 } which sorts descending. let sortedArray = numbers.sorted(by: { $0 < $1 }) sorts ascending. let sortedArray = numbers.sorted() sorts ascending by default. let sortedArray = numbers.sorted(by: { $1 > $0 }) reverses the comparison incorrectly.
  3. Final Answer:

    let sortedArray = numbers.sorted(by: { $0 > $1 }) -> Option D
  4. Quick Check:

    Descending sort uses $0 > $1 [OK]
Hint: Use $0 > $1 for descending sort [OK]
Common Mistakes:
  • Using $0 < $1 for descending
  • Forgetting to provide closure for custom order
  • Confusing parameter order in closure
3. What is the output of the following Swift code?
let names = ["Anna", "Bob", "Charlie"]
let sortedNames = names.sorted(by: { $0.count < $1.count })
print(sortedNames)
medium
A. ["Bob", "Charlie", "Anna"]
B. ["Bob", "Anna", "Charlie"]
C. ["Charlie", "Anna", "Bob"]
D. ["Anna", "Bob", "Charlie"]

Solution

  1. Step 1: Understand the sorting rule

    The closure sorts by string length ascending: shorter names come first.
  2. Step 2: Apply sorting to the array

    "Bob" has 3 letters, "Anna" 4, "Charlie" 7. So order is ["Bob", "Anna", "Charlie"].
  3. Final Answer:

    ["Bob", "Anna", "Charlie"] -> Option B
  4. Quick Check:

    Sort by length ascending = ["Bob", "Anna", "Charlie"] [OK]
Hint: Sort by $0.count < $1.count for shortest first [OK]
Common Mistakes:
  • Sorting alphabetically instead of by length
  • Confusing < with > in closure
  • Expecting original order
4. Identify the error in this Swift code that tries to sort an array of tuples by the second value:
let items = [("a", 3), ("b", 1), ("c", 2)]
let sortedItems = items.sorted(by: { $0.1 > $1.1 })
print(sortedItems)
medium
A. There is no error; the code sorts descending by second value.
B. The tuple elements cannot be accessed by index like $0.1.
C. The closure parameters should be $1.1 > $0.1 for ascending order.
D. The sorting closure must return an Int, not Bool.

Solution

  1. Step 1: Check tuple access syntax

    Accessing tuple elements by $0.1 and $1.1 is correct in Swift closures.
  2. Step 2: Verify sorting closure logic

    The closure returns true if first element's second value is greater, sorting descending by second value.
  3. Final Answer:

    There is no error; the code sorts descending by second value. -> Option A
  4. Quick Check:

    Tuple access and Bool return are correct [OK]
Hint: Tuple elements accessed as $0.1; closure returns Bool [OK]
Common Mistakes:
  • Thinking tuple elements can't be accessed by index
  • Expecting closure to return Int
  • Confusing ascending and descending order
5. You have an array of dictionaries representing people: let people = [["name": "Alice", "age": 30], ["name": "Bob", "age": 25], ["name": "Charlie", "age": 30]]. How do you sort this array first by age ascending, then by name ascending if ages are equal?
hard
A. people.sorted { $0["age"] as! Int < $1["age"] as! Int && $0["name"] as! String < $1["name"] as! String }
B. people.sorted(by: { $0["age"] as! Int > $1["age"] as! Int || $0["name"] as! String > $1["name"] as! String })
C. people.sorted { ($0["age"] as! Int, $0["name"] as! String) < ($1["age"] as! Int, $1["name"] as! String) }
D. people.sorted(by: { $0["name"] as! String < $1["name"] as! String })

Solution

  1. Step 1: Understand sorting by multiple keys

    Sorting by age ascending, then name ascending means comparing tuples of (age, name).
  2. Step 2: Check each option's logic

    people.sorted { ($0["age"] as! Int, $0["name"] as! String) < ($1["age"] as! Int, $1["name"] as! String) } compares tuples directly, which sorts by age first, then name if ages equal. people.sorted { $0["age"] as! Int < $1["age"] as! Int && $0["name"] as! String < $1["name"] as! String } uses && which fails for correct ordering. people.sorted(by: { $0["age"] as! Int > $1["age"] as! Int || $0["name"] as! String > $1["name"] as! String }) sorts descending and mixes conditions incorrectly. people.sorted(by: { $0["name"] as! String < $1["name"] as! String }) sorts only by name.
  3. Final Answer:

    people.sorted { ($0["age"] as! Int, $0["name"] as! String) < ($1["age"] as! Int, $1["name"] as! String) } -> Option C
  4. Quick Check:

    Tuple comparison sorts by multiple keys [OK]
Hint: Compare tuples (age, name) for multi-level sorting [OK]
Common Mistakes:
  • Using && instead of tuple comparison
  • Sorting only by one key
  • Mixing ascending and descending incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard