Hi

could someone please explain this? how does the closure work to change the sorting.

how are the two parameters $0 and $1 supplied to the closure?

many thanks

DK

Hi

could someone please explain this? how does the closure work to change the sorting.

how are the two parameters $0 and $1 supplied to the closure?

many thanks

DK

how does the closure work to change the sorting

To sort al list, you have to compare this element to that element, then move this element over here, then start over and compare that element to this element, then switch them if necessary, then compare the second element to the fourth element, and reorder them, etc. etc. until youâ€™ve made thousands of comparisons. The closure tells swift which of two elements in a single comparison is bigger. Here are some examples:

```
let result = ["bxa", "ab", "acd", "x"].sorted() {
$0.count > $1.count
}
--output:--
["bxa", "acd", "ab", "x"]
```

If `$0.count > $1.count`

is true, then $0 is considered to be bigger than $1, else $1 is considered to be bigger than $0. As you can see, bigger comes first in the sorted array. To sort things, you have to know which elements are bigger and which elements are smaller.

```
let result = [[6], [1,1,1], [2,3]].sorted() {
$0.reduce(0, +) > $1.reduce(0, +)
}
--output:--
[[6], [2, 3], [1, 1, 1]]
```

```
let result = [[6, 1], [1,3,1], [2,0,1]].sorted() {
$0[1] > $1[1]
}
--output:--
[1, 3, 1], [6, 1], [2, 0, 1]]
```

â€“

```
class Money {
let val: Int
init(val: Int) {
self.val = val
}
}
let monies = [Money(val: 5), Money(val: 2), Money(val: 4)]
let results = monies.sorted() {
$0.val > $1.val
}
--output:--
[{val 5}, {val 4}, {val 2}]
```

How are the arguments supplied to the closure?

```
func bubbleSort(arr: [Int], sortFunc: (Int, Int) -> Bool) -> [Int] {
var data = arr
for i in 0..<(data.count-1) {
for j in 0..<(data.count-i-1) where sortFunc(data[j+1], data[j]) {
data.swapAt(j, j + 1)
}
}
return data
}
let results = bubbleSort(arr: [3, 1, 2, 4]) {
$0 < $1
}
print(results)
```

Hi,

many thanks for the explanation, it was bugging me all day yesterday!

The article below also explains it quite nicely.

DK

Sorry, I had to stop in the middle of my post. I wanted to post an example of a sort function, but I see you already found a good resource for â€śhigher orderâ€ť functions. I added a sort function to my previous post anyway.

This topic was automatically closed after 166 days. New replies are no longer allowed.