Custom sorting with closures

Closures come in handy when you start looking deeper at collections. In Chapter 8, you used array's sort facility to sort an array. By specifying a closure, you can customize how things are sorted. You call sorted() to get a sorted version of the array as so:

let names = ["ZZZZZZ", "BB", "A", "CCCC", "EEEEE"]

names.sorted()

// ["A", "BB", "CCCC", "EEEEE", "ZZZZZZ"]

By specifying a custom closure, you can change the details of how the array is sorted. Specify a trailing closure like so:

names.sorted {

$0.characters.count > $1.characters.count

}

// ["ZZZZZZ", "EEEEE", "CCCC", "BB", "A"]

Now the array is sorted by the length of the string with longer strings coming first.

results matching ""

    No results matching ""