1

How can a dictionary be sorted, by its keys, in the order listed in an array? See example:

Dictionary to sort:

var item = [
    "itemName":"radio",
    "description":"battery operated",
    "qtyInStock":"12",
    "countOfChildren":"5",
    "isSerialized":"0"
]

Order in which the keys should be sorted:

let sortOrder = [
    "itemName",
    "qtyInStock",
    "countOfChildred",
    "description",
    "isSerialized"
]

I have tried the following in Playground:

var sortedItem = Dictionary<String, String>()

for i in sortOrder {
    sortedItem[i] = item[i]
}

While viewing the value history in Playground displays everything in the correct order, the resulting dictionary is in a seemingly random order.

Michael Voccola
  • 1,827
  • 6
  • 20
  • 46

2 Answers2

1

A dictionary, by definition, doesn't have an order.

However, you can have an array of sorted items by touples or implement your sorted dictionary.

Community
  • 1
  • 1
Tiago Almeida
  • 14,081
  • 3
  • 67
  • 82
1

As mentioned by Tiago, a Dictionary by definition doesn't have an order. It is essentially a mapping of keys to values. I would recommend one of two approaches.

If the ordering you wish to achieve is manual as your question makes it seem. I would create an array to hold ordered keys. Then, at any point you need to, you can cycle through the array (which is order) and print out all of the values found in the dictionary. They will inherently be printed out using the ordered array of keys.

If the ordering is something than be done programmatically, you could grab a reference to all of the keys by doing myDictionary.keys.array. You could then sort the array, then once again, iterate through the array and grab the values from the dictionary.

Example:

let myKeys = myDictionary.keys.array
// sort the keys
for key in myKeys {
    println(myDictionary[key])
}

Hope that helps.

Kyle
  • 14,036
  • 11
  • 46
  • 61