Sorting a List of Fruits with Custom Order in Swift
📖 Scenario: You have a list of fruits, but you want to sort them in a special order that you decide, not just alphabetically.
🎯 Goal: Build a Swift program that sorts a list of fruits using a custom order you define.
📋 What You'll Learn
Create an array called fruits with the exact values: "apple", "banana", "cherry", "date", "elderberry"
Create a dictionary called priority that assigns each fruit a number representing its custom order
Use the sorted(by:) method with a custom comparator closure to sort fruits by the priority values
Print the sorted array exactly as shown
💡 Why This Matters
🌍 Real World
Sorting items by custom rules is common in apps like shopping lists, games, or task managers where order matters beyond simple alphabetical sorting.
💼 Career
Understanding how to use custom comparators and sorting is important for software developers working on user interfaces, data processing, and any feature that requires ordered data.
Progress0 / 4 steps
1
Create the fruits array
Create an array called fruits with these exact string values in this order: "apple", "banana", "cherry", "date", "elderberry"
Swift
Hint
Use square brackets [] to create an array and separate the fruit names with commas.
2
Create the priority dictionary
Create a dictionary called priority that assigns these exact values: "banana": 1, "apple": 2, "date": 3, "cherry": 4, "elderberry": 5
Swift
Hint
Use square brackets [] with key-value pairs separated by colons and commas.
3
Sort fruits using the custom priority
Create a new constant called sortedFruits that sorts fruits using sorted(by:) with a closure comparing the priority values of two fruits
Swift
Hint
Use fruits.sorted { priority[$0]! < priority[$1]! } to sort by priority values.
4
Print the sorted fruits
Print the sortedFruits array exactly using print(sortedFruits)
Swift
Hint
Use print(sortedFruits) to show the sorted list.
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
Step 1: Understand the purpose of sorted(by:)
This method sorts elements of an array based on a closure that defines the order.
Step 2: Compare with other array methods
Unlike filtering or reversing, sorted(by:) changes order based on a custom rule.
Final Answer:
It sorts an array using a custom rule you provide. -> Option A
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
Step 1: Understand sorting order
To sort descending, the comparator must return true when the first element is greater than the second.
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.
Final Answer:
let sortedArray = numbers.sorted(by: { $0 > $1 }) -> Option D
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
Step 1: Understand the sorting rule
The closure sorts by string length ascending: shorter names come first.
Step 2: Apply sorting to the array
"Bob" has 3 letters, "Anna" 4, "Charlie" 7. So order is ["Bob", "Anna", "Charlie"].
Final Answer:
["Bob", "Anna", "Charlie"] -> Option B
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
Step 1: Check tuple access syntax
Accessing tuple elements by $0.1 and $1.1 is correct in Swift closures.
Step 2: Verify sorting closure logic
The closure returns true if first element's second value is greater, sorting descending by second value.
Final Answer:
There is no error; the code sorts descending by second value. -> Option A
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 })