-3

I am trying to build a generic function that arranges the keys of a dictionary in ascending order. The code below doesn’t perform the task correctly. How do I resolve it?

func sortKeysx<T: Comparable>(value: [T:T])->[T:T] {
        let sorted = value.sorted{ $0.key < $1.key }
        return Dictionary(uniqueKeysWithValues: sorted)
    }
    
    
sortKeysx(value: [5.0:3, 4.0:2, 3.0:7, 2.0:1])

output: [3.0: 7.0, 4.0: 2.0, 5.0: 3.0, 2.0: 1.0]
Mayowa Paul
  • 65
  • 1
  • 6
  • Does this answer your question? [Sort Dictionary by keys](https://stackoverflow.com/questions/25377177/sort-dictionary-by-keys) – Noah Aug 06 '21 at 03:21
  • The gist of the answers given above: You can iterate over a `Dictionary` in key order, and you can use that iteration order to read the keys and values into order-preserving data structures like `Array`s or an `OrderedDictionary`. But `Dictionary`s aren't order-preserving, so don't use one if you care about the order. – Noah Aug 06 '21 at 03:24
  • Please provide an example, I don't quite understand – Mayowa Paul Aug 06 '21 at 03:26
  • 1
    Can you go to the link in my first comment? They explain it pretty well there. – Noah Aug 06 '21 at 03:27
  • Don't expect a Dictionary preserve the key order. Use different data structure and logic to achieve your goal. Even if the compiler implementation does preserve key order, the specification of the data structure does not. So don't treat it as guaranteed. – Ricky Mo Aug 06 '21 at 04:05

1 Answers1

1

The Dictionary(uniqueKeysWithValues: sorted) call does not provide any guarantee to preserve the order of keys.

You may want to use an OrderedDictionary instead.

Tarun Tyagi
  • 9,364
  • 2
  • 17
  • 30