Sort Items In Array By Desc In Swift
Code snippet for how to Sort Items In Array By Desc In Swift with sample and detail explanation
Sorting items in descending order within an array in Swift is a routine task that many programmers will face at some point. This article provides a step-by-step guide on implementing this functionality into your own Swift programs.
Code snippet for Sorting Items In Array By Desc In Swift
Here’s a practical code snippet that shows how to sort items in an array in descending order in Swift.
var numbersArray = [1, 5, 3, 6, 2, 7, 8]
numbersArray.sort(by: >)
print(numbersArray)
Code Explanation for Sorting Items In Array By Desc In Swift
Let’s break down this code to understand how it functions.
First, we declare numbersArray
to hold some integer values.
var numbersArray = [1, 5, 3, 6, 2, 7, 8]
Next, we use the sort(by:)
function to sort the array. The major part here, is the >
operator we pass in as the sorting criteria. This tells Swift to sort the array in descending order.
numbersArray.sort(by: >)
Finally, we print out the sorted array to see the results.
print(numbersArray)
Reading from the console, you’d notice that numbersArray
will print out [8, 7, 6, 5, 3, 2, 1]
, instead of the initial [1, 5, 3, 6, 2, 7, 8]
we defined at the start of the script. This proves that the sort(by:)
function has sorted numbersArray
in descending order.
And that’s it! With just a couple of lines of code, you can sort the items in an array by descending order in Swift. Keep in mind that the sort(by:)
function can also take a closure, allowing for more complex sorting algorithms, but for simple ascending and descending sorts, the <
and >
operators often suffice.