0

I have a dictionary in Swift 4 declared as:

   /* Not a compilable code, excuse for brevity as it is a long map */
   let map: [String:[String]] = ["16:9" : Array1, "4:3" : Array2,...]

Then I invoke

  let keys = Array(map.keys)
  let first = keys.first!

Problem is order in keys is not the same as order in map. The first value returned is not "16:9" as a result. Why is it so and how to fix it? I need keys in the same order.

EDIT: As several comments point of, dictionary is unordered so I shouldn't rely on ordering. In that case, the question is what datatype should I use to accomplish my task?

Deepak Sharma
  • 5,577
  • 7
  • 55
  • 131
  • A `Dictionary` is an unordered collection by definition, so you shouldn't rely on any ordering of the keys. – Dávid Pásztor Nov 05 '18 at 09:50
  • Dictionary aren't sorted. So there is no guarantee that tomorrow you won't get "4:3" first if you iterate your dictionary. – Larme Nov 05 '18 at 09:51
  • What is the way out? I need it in same order. – Deepak Sharma Nov 05 '18 at 09:52
  • Dictionnary are not sorted. See this answer https://stackoverflow.com/a/29603477/5464805 – Olympiloutre Nov 05 '18 at 09:52
  • 1
    The real question is why do you need a dictionnary if you expect to get an ordered list? Why not using a simple Array of tuples instead? – Olympiloutre Nov 05 '18 at 09:53
  • I need to display keys in the order declared in dictionary. Should i be storing keys separately that means? That doesn't look good to me as the list of keys could be long. What other data structure should i use if I need ordering? – Deepak Sharma Nov 05 '18 at 09:55
  • @DeepakSharma the question is, where is that Dictionary coming from, how is it initialised? – Dávid Pásztor Nov 05 '18 at 09:58
  • I initialise it statically in code. I have a host of resolutions against every aspect ratio. – Deepak Sharma Nov 05 '18 at 09:59
  • In other words, I need ordered [key:value] pairs as I initialized statically in code. What is the way to achieve this? – Deepak Sharma Nov 05 '18 at 10:01
  • @DeepakSharma if you initialise it statically using hardcoded values, there's no need to order the keys again since you should know the ordering. However, you can use an array of tuples to convert the key-value pairs of the dictionary to an ordered key-value collection, but you have to be aware that this way you lose the ability to index the collection using the dictionary keys. – Dávid Pásztor Nov 05 '18 at 10:13
  • We need more information about what you're trying to do to help you choose an appropriate data structure. Also some measure of the size of the list of items. If you're statically setting up this data then you can use an array but, as mentioned above, lookup is now linear (or can do binary lookup if it's ordered by values), so that depends on number of items in your list, how often you need to look things up in it, and if the key values are ordered by value. – Dad Nov 05 '18 at 18:11

0 Answers0