0

I'm trying to create a dictionary from sorted array of times (which are string). Here is the code:

  var usernameCommentsSorted: [String : [String : String]] = [:]
  print("not sorted: \(Array(usernameComments.keys))")
  let sortedKeys = Array(usernameComments.keys).sorted()
  print("sorted: \(sortedKeys)")

  for time in sortedKeys {

    print("time in for loop -- \(time) --")
    usernameCommentsSorted[time] = ["F" : "F"]

  }

  print("sorted final dictionary: \(usernameCommentsSorted)")

and here's the output:

image

So my question is, why is the dictionary not receiving the times as the for in loop goes? Maybe I'm missing some behaviour of dictionaries.

Thank you in advance.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116

1 Answers1

0

Array has value sematics in Swift. When you call Array(usernameComments.keys) it creates a copy of the dictionary keys. When you call .sorted you are calling the version that creates a copy (.sort does an inplace sort). In any case you cannot mutate the keys array of a dictionary. You can, however keep a separate sorted copy of the array, which you need to update any time the dictionary is modified. Then you can iterate throught he dictionary in sorted order like:

for key in sortedKeys {
   print(dictionary[key]!)
}

Apple does have an objective C class that is an ordered hashtable. Consider whether or not NSMutableOrdered set is a better data structure choice for your use case. As the name implies it has unique keys that you can order.

Josh Homann
  • 15,933
  • 3
  • 30
  • 33