Sorting an Array in Swift (Ascending and Descending order)


In this tutorial, you are going to learn how to sort an array in Swift with the help of examples. In the examples, I have covered the sorting of array elements in both ascending and descending order.

In Swift, there are two built-in methods sort() and sorted(). We can use any one of these methods to sort elements of an array.

Both the sort() and sorted() methods can sort an array in the same way, but there is a key difference between these two methods.

The sort() method mutates or modifies the original array. On the other hand, the sorted() method keeps the original array unchanged and returns a new array with the elements sorted.

Sorting array in ascending order

Let’s see examples of sorting a Swift array in ascending order:

Example 1: Using sort() and sort(by:) method

The sort() and sort(by:) method modifies the original array and sort the elements of the array in place.

See the program below:

var myNumbers = [5, 1, 11, 9, 7, 3]

myNumbers.sort()

print(myNumbers)

Output:

[1, 3, 5, 7, 9, 11]

In the above example, we have used the sort() method. We can also do this by using sort(by: <):

myNumbers.sort(by: <)

It will give the same result as the previous one. The by: < argument tells our array to be sorted in ascending order. If we use the sort() method without passing by:, then by default it will sort the array in ascending order.

Example 2: Using sorted() and sorted(by:) method

The sorted() and sorted(by:) method doesn’t modify the existing array. It creates a new array:

var myNumbers = [5, 1, 11, 9, 7, 3]

let sortedArray = myNumbers.sorted()

print(sortedArray)

Output:

[1, 3, 5, 7, 9, 11]

We can also use myNumbers.sorted(by: <) and the result will be the same:

let sortedArray = myNumbers.sorted(by: <)

Sorting array in descending order

Now its time to see examples of sorting Swift array in descending order:

Example 1: Using sort(by:) method

To sort an array in descending order, we have to use the sort(by:) method. Here we can’t use the sort() method. This is because, if we don’t pass any argument in the method, it will sort the array in ascending order by default. So we have to pass the by: > argument.

Below is the example with the corresponding output for sorting a Swift array in descending order using the sort(by:) method:

var myNumbers = [5, 1, 11, 9, 7, 3]

myNumbers.sort(by: >)

print(myNumbers)

Output:

[11, 9, 7, 5, 3, 1]

In the above example, the original array has been modified during sorting it.

Example 2: sorted(by:) method

below is the example of sorting an array using the sorted(by:) method:

let myNumbers = [5, 1, 11, 9, 7, 3]

let sortedArray = myNumbers.sorted(by: >)

print(sortedArray)

Output:

[11, 9, 7, 5, 3, 1]

You can notice that this time the original array is unchanged and we have created a new array with its elements sorted by descending order.