11.2. Decreasing order

Unfortunately, it is not as simple to sort an array in a reversed (decreasing) order as it is to sort it in an increasing order. We need to write a comparator function or closure and use sort(by: <comparator>)) to do it.

Think about how you would sort an array of items.

  • You'd probably iterate through the array and compare each item with the other items to see where to put the current item. You need to compare two values to figure out which one is bigger or which one is smaller.

  • Now, sorting in increasing order is the default behavior, so you do not need to modify the comparator logic of Swift. However, sorting in decreasing is not a default behavior, so you need to specify how you would compare each pair of values.

Let's define our compare function decreasing() as follows:

//function to compare two values to find which if value1 is greater than value2...
func decreasing(value1:Int, value2:Int)->Bool{
    return value1 > value2
}

In increasing order, the comparator checks if the first value of a pair of values is smaller than the second value. If yes, then do not swap; else, swap. In the above code, we are reversing the order. So we are checking if the first value is greater than the second value, then do not swap; they are in the correct order.

Then we call the sort(by: ..) as follows:

var arrayOfInt:[Int] = [1,56,89,23,4,6]

//sort the array by using the comparator function decreasing...
arrayOfInt.sort(by: decreasing)

print(arrayOfInt)
//prints: [89, 56, 23, 6, 4, 1]

Do it using closures (not functions)

We can concisely write code without writing a different function using closures. And it would be best if you got used to this style. As we have seen, we can use a function as a variable, or conversely, we can write code inline instead of a variable. So let's write a closure directly inside the sort(by: ...) as follows:

The difference between the previous code and the above code is that instead of writing a separate function decreasing(), we are writing the closure inside the sort(by:..) call.

Now let's see what happens:

You can shorten it even more. I did not want to give you an overdose yet. 😂

Last updated

Was this helpful?