Back to Blog

Swift with Copilot: Sort a list of numbers

Sandy LaneSandy Lane

Video: Swift with Copilot: Sort a list of numbers by Taught by Celeste AI - AI Coding Coach

Watch full page →

Swift with Copilot: Sort a List of Numbers

Sorting a list of numbers is a fundamental task in programming, and Swift makes it straightforward with built-in methods. In this example, we use Swift's array sorting capabilities to organize numbers in ascending order, demonstrating how concise and readable Swift code can be.

Code

// Define an array of unsorted numbers
var numbers = [42, 7, 19, 3, 88, 56]

// Sort the array in ascending order using the sorted() method
let sortedNumbers = numbers.sorted()

// Print the sorted array
print("Sorted numbers: \(sortedNumbers)")

// Alternatively, sort the original array in place using sort()
numbers.sort()
print("Numbers sorted in place: \(numbers)")

Key Points

  • Swift arrays have a built-in sorted() method that returns a new sorted array without modifying the original.
  • The sort() method sorts the array in place, modifying the original array.
  • Both methods sort elements in ascending order by default.
  • You can provide a custom closure to sorted() or sort() to define custom sorting criteria.