I always got confused as to what’s the end result my sort. I wasn’t sure if it would end up being ascending or descending.
The ultimate trick is to not think of up vs down. Instead think of increasing/decreasing from left to right.
We perceive arrays as horizontal beings. Hence left and right make more sense vs up and down
let nums = [1,4,2,3]
let sorted_nums = arr.sorted(by: {
$0 < $1 // left is smaller [1,2,3,4] i.e. ascending
})
If you see $0 < $1
then left side is smaller than the next item. i.e. it’s ascending.
let nums = [1,4,2,3]
let sorted_nums = arr.sorted(by: {
$0 > $1 // left is bigger [4,3,2,1] i.e. descending
})
If you see $0 > $1
then right side is smaller than the next item. i.e. it’s descending.
Similarly writing array.sorted(by: <)
is identical.
Alternate way:
array.sorted(by: <)
will make it decreasing.array.sorted(by: >)
will make it increasing.
And if I don’t pass a block?
It will make the array increasing. Increasing is more natural as that’s how we’d list numbers from 1…n and we almost never list numbers n…1.
let nums = [1,4,2,3]
print(nums.sorted()) // [1,2,3,4]
$0 vs $1
Never place the $1
on the left side when sorting. $0
is the first number, $1
is the second number in the comparison. If you switch them then the order will get reversed.