Home
Swift
Sort Dictionary: Keys and Values
Updated Sep 16, 2023
Dot Net Perls
Sort dictionary. In 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.
sort
Dictionary
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.
Example. 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.
Part 1 We create a dictionary with 3 keys, each with an associated value. The keys are Strings, and the values are Ints.
Part 2 Here we convert the dictionary into an array by using Array(). This gives us an array of Entry instances.
Part 3 We sort in an ascending way with the "less than" character, which is shorthand for a closure than sorts the elements.
Part 4 We display the elements after the first sorting operation. The keys are now ordered alphabetically.
Part 5 To sort by values, we can specify a closure, which is longer to type out and read, but works in a similar way.
Part 6 Finally we display the entries in our array again. They have been sorted now by the value (the Ints).
// 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 16, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen