Home > Net >  OrderedDictionary can't convert value of type '[String : Double]' to specified type &
OrderedDictionary can't convert value of type '[String : Double]' to specified type &

Time:06-17

I'm trying to use OrderedDictionary from Collections and I'm getting the following error when trying to convert a Dictionary to OrderedDictionary.

Cannot convert value of type '[String : Double]' to specified type 'OrderedDictionary<Key, Value>'

let values: [String: Double]

let sortedDict: OrderedDictionary<String, Double> = values

CodePudding user response:

The compiler won't let you cast it directly. Instead, pass values to the initializer.

let sortedDict: OrderedDictionary<String, Double> = OrderedDictionary(uniqueKeysWithValues: values)

CodePudding user response:

You can use the uncheckedUniqueKeysWithValues initialiser:

let sortedDict = OrderedDictionary(uncheckedUniqueKeysWithValues: values)

It is safe to use this initialiser because values is a dictionary, whose keys are always unique. This is "somewhat faster" in optimised builds, according to the documentation comments.

However, unlike the name suggests, the dictionary created this way is not sorted. "Ordered" just means that the entries are guaranteed to be in insertion order. Since the entries in values are unordered, sortedDict here will get the entries of value in a random order, and they will stay in that order in sortedDict.

If you want it to be sorted, by keys for example, you need to sort it yourself:

let sortedDict = OrderedDictionary(uncheckedUniqueKeysWithValues: 
    values.sorted { $0.key < $1.key }
)
  • Related