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

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.

Go ahead and copy the below example, run it multiple times, you will see that the dictionary will change every time the output and print different keys each time. But, the KeyValuePair one will always print the same key/value in the same order.

Using a KeyValuePairs to obtain a orderer key/value pairs in a collection
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

I'm an iOS Software Engineer mostly. Known as phynet in the internez. I'm me, full of memory failure and lovely karma.

 

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

Leave a Reply

Your email address will not be published. Required fields are marked *