1

The following code attempts to sort the keys of a dictionary in ascending order. For some reason "6:58" and "7:56" are not sorted correctly but the others are. What could be the cause of this?

print(dictionary.keys)
sortedKeys = dictionary.keys.sorted(by: <)
print(sortedKeys)

["7:56", "14:57", "11:57", "6:58", "10:59", "17:59"]
["10:59", "11:57", "14:57", "17:59", "6:58", "7:56"]

2 Answers2

2

This happens because the strings are sorted as strings, i.e. lexicographically. Therefore, "1" precedes both "6" and "7", so the list is sorted correctly.

A quick fix to this problem is to add zeros to four-character strings representing time, i.e. change your list to

["07:56", "14:57", "11:57", "06:58", "10:59", "17:59"]

This list would sort correctly. If this is not an option, use a custom comparer, as described in this Q&A.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

It's because they're strings, and : is sorted as a character. Really you're doing this:

var simpleD = ["7:", "14:", "11:", "6:", "10:", "17:"]
print(simpleD.sorted(by: <))

Which results in:

["10:", "11:", "14:", "17:", "6:", "7:"]

If you want to sort as strings, you need to pre-pend "0" to the keys whose values are less than 10. The better solution would be to store them in numerical form. If they're times, store in minutes rather than hours or minutes, so you can use a numeric key.

David S.
  • 6,567
  • 1
  • 25
  • 45