“KeyValuePairs” in Swift or how to create an ordered dictionary

Sofia Swidarowicz
2 min readJan 7, 2021

I’ve posted this entry firstly in my my personal blog, and commented about it on Twitter and it seems that people were very enthusiastic about it, so I’ve decided to post it here as well.

I was facing one day with the strange –at the time– task to send to a third party application an ordered collection key/value pair from an iOS app.

I then wondered if there was a collection type, capable of doing such thing in Swift since my knowledge at the time of a dictionary in this language was pretty basic:

1.- It’s a type of hash table, hence their elements have to conform to the Hashable protocol in order to make a fast key lookup

2.- They cannot have duplicates keys

Then I started to search about collection types in Swift, since I haven’t used an ordered key/value dictionary before.

First thing I learned was that using KeyValuePairs allows you to create a “dictionary” with duplicate keys and is much slower when searching for a key than a true dictionary, so you must be careful when using one of these, since the search could be much less efficient.

In my particular case I didn’t need to do any filter, just send exactly what I was adding, so I had no problem in that area ;D

In this image you can see that the common dictionary will print his values in different order each time, but the KeyValuePair will always print it in the same order that were added.

If you want to try it, go ahead and copy below example, run it multiple times, you will see that the dictionary will change every time the output and print in different order their values, which makes sense. Try to add a duplicated key, to it, you will see an error. Now check the KeyValuePairs, see?

let recordTimes: KeyValuePairs<String,Double> =
["Florence Griffith-Joyner": 10.49,
"Florence Griffith-Joyner": 10.59,
"Evelyn Ashford": 10.76,
"Evelyn Ashford": 10.79,
"Marlies Gohr": 10.81]
let recordTimesNotOrdered =
["Florence Griffith-Joyner": 10.49,
"Evelyn Ashford": 10.76,
"Marlies Gohr": 10.81]
print(recordTimes.first as Any)
print(recordTimesNotOrdered.first as Any)

In other languages this type of collection is called associative arrays, map or symbol table.

I hope this post helps if needed.

Also, for more information about this kind of dictionary, you can check Apple’s doc here:

https://developer.apple.com/documentation/swift/keyvaluepairs

--

--

Sofia Swidarowicz

iOS Software Engineer at eDreams Odigeo. X-files lover; the series, not the x-files in programming. No one loves X-files in programming. Instagram: @phyonline