The sorted
function takes a closure which defines the ordering of any two elements. The sorting algorithm does a series of comparisons between items, and uses the closure to determine the ordering amongst them.
Here's an example which prints out all the comparisons done in the sorting of an example array of numbers:
let numbers = [0, 9, 1, 8, 2, 7, 3, 6, 4, 5]
let sorted = numbers.sorted { (a: Int, b: Int) -> Bool in
let result = a < b
print("\(a) is \(result ? "" : "not") before \(b)")
return result
}
print(sorted)
$0
and $1
are implicit closure parameters. They're names implicitly given to the parameters of a closure. They're often used in cases where the names given to parameters of a closure are rather arbitrary, such as in this case.
In your example, the closure behaves as if it was like so:
let numbers = [0,2,1]
let sortedNumbers = numbers.sorted { leftElement, rightElement in
return leftElement > rightElement
}
As you can see leftElement
and rightElement
don't add much information to the code, which is why it's preferred to use implicit closure parameters in a case like this.