0
0
Swiftprogramming~15 mins

Sorted and custom comparators in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use print(sortedFruits) to show the sorted list.