Sort
dictionaryIn Swift 5.8, the dictionary is a collection that does not have any specific ordering to its keys and values. But we can copy the dictionary's contents and sort the entries.
By converting the dictionary into an array, we can access each Dictionary
entry for sorting. We can specify how to sort entries with a closure.
To begin, we have a dictionary and want to sort its keys and values in various ways. We use an ascending sort here, but descending could be done as well.
Array()
. This gives us an array of Entry instances.// Part 1: create a dictionary. let animals = ["beta": 0, "zeta": 900, "alpha": 10] // Part 2: Convert the dictionary into an array. var copy = Array(animals) // Part 3: sort by key of each element from low to high (alphabetical order). copy.sort(by: <) // Part 4: loop over and display sorted elements. for element in copy { print(element) } print() // Part 5: sort by value with closure. copy.sort(by: { (a, b) -> Bool in return a.value < b.value }) // Part 6: display again. for element in copy { print(element) }(key: "alpha", value: 10) (key: "beta", value: 0) (key: "zeta", value: 900) (key: "beta", value: 0) (key: "alpha", value: 10) (key: "zeta", value: 900)
By converting other types like Dictionary
into arrays, we can access powerful built-in functions like sort()
. This gives us a convenient way to modify and display data.