Tim Dietrich

Custom Software Developer

Home Services Portfolio Blog About Contact Newsletter

Swift: Sorting Dictionaries

To say that Swift dictionaries are powerful and versatile is quite an understatement. I find myself using them very often and in a wide variety of ways, especially in the data-driven iOS apps that I've been working on.

Earlier today, I was working on an app in which I needed to present data stored as a dictionary. That's usually not a problem. However, in this case I needed to present the data in order based on the key values. It took a little while, but I did find a way to pull this off. What follows is a quick review of how I did it.

For this example, I'll use a simple dictionary. I'll be working with ICD-10 medical billing codes, and storing them in a dictionary where the key is the alphanumeric code and the value is the code's description.

Let's start by defining the dictionary. Both the keys and values will be strings.

var codes = [String: String]()

Now let's add a few values, and do so in a somewhat random order.

codes["W59.21"] = "Bitten by turtle"
codes["V91.07"] = "Burn due to water-skis on fire"
codes["W22.02"] = "Walked into lamppost"
codes["R46.1"] = "Bizarre personal appearance"
codes["W16.221"] = "Fall in (into) bucket of water causing drowning and submersion"

Here's what the dictionary looks like.

["V91.07": "Burn due to water-skis on fire", "W59.21": "Bitten by turtle", "R46.1": "Bizarre personal appearance", "W16.221": "Fall in (into) bucket of water causing drowning and submersion", "W22.02": "Walked into lamppost"]

Notice that the entries are in the order in which we added them. If we were to iterate over them, that's the order that they would be presented.

Again, the goal is to present the dictionary in order based on the keys. To do that, start by getting the dictionary's keys as an array. I'm going to use the "keys" method of Swift's dictionary datatype, which returns a collection of the keys, which can then be used to create an array. (It's worth mentioning that a "values" method is also supported.) Here's what the code looks like.

let unSortedCodeKeys = Array(codes.keys)

Now that we have the dictionary keys as an array, we can easily sort them by using the "sort" method of the array datatype, as seen here.

let sortedCodeKeys = unSortedCodeKeys.sort(<)

The sort method is being called with a "<" parameter, indicating that the values should be sorted in ascending order. You could also sort in descending order by using a ">" parameter.

So far, so good. We have the keys in sorted order, and we can iterate over them. But what about the corresponding values?

Well, remember that we originally started with a dictionary. So all that we need to do is iterate over the sorted keys, and use them to get the correct corresponding values. Here's what that looks like.

for code in sortedCodeKeys {
    // Display the code (key) and description (value).
    print("\(code): \(codes[code])")

And here's the output.

R46.1: Optional("Bizarre personal appearance")
V91.07: Optional("Burn due to water-skis on fire")
W16.221: Optional("Fall in (into) bucket of water causing drowning and submersion")
W22.02: Optional("Walked into lamppost")
W59.21: Optional("Bitten by turtle")

That's all there is to it!

If you're interested, here's a Swift playground file that shows the technique demonstrated above.