Back to Blog

Swift with Copilot: Sort list ascending and descending

Sandy LaneSandy Lane

Video: Swift with Copilot: Sort list ascending and descending by Taught by Celeste AI - AI Coding Coach

Watch full page →

Swift with Copilot: Sort List Ascending and Descending

Sorting arrays is a fundamental task in Swift programming. This example demonstrates how to sort a list of numbers in both ascending and descending order using Swift's built-in sorting methods, making it easy to organize data efficiently.

Code

// Define an array of integers
var numbers = [5, 2, 9, 1, 7]

// Sort the array in ascending order
let ascending = numbers.sorted()
// ascending is [1, 2, 5, 7, 9]

// Sort the array in descending order using a closure
let descending = numbers.sorted { $0 > $1 }
// descending is [9, 7, 5, 2, 1]

// Print results
print("Ascending order: \(ascending)")
print("Descending order: \(descending)")

Key Points

  • Use the sorted() method to get a new array sorted in ascending order by default.
  • Pass a closure to sorted(by:) to customize the sorting order, such as descending.
  • The closure compares two elements and returns true if the first should be ordered before the second.
  • Original arrays remain unchanged when using sorted(), preserving immutability.