I have a dictionary, [String : Double]
with the following data:
Museum1 : 8785.8971799638
Museum2 : 34420.9643422388
Museum3 : 826.467789130732
Museum4 : 304120.342151219
I'd like to sort the dictionary by the double value. I did some research, but all of the examples are deprecated for the current version of Swift
I've tried using this code from Sort Dictionary by values in Swift:
for (k,v) in Array(self.museumsDic).sorted({$0.0 < $1.0}) {
println("\(k):\(v)")
}
But it doesn't work. How can I sort the dictionary by its values?
It is not clear what your expectations are. There is really no such thing as a sorted dictionary. Your code is basically correct except for a misplaced parenthesis. I tried this:
let d = ["Museum1":8785.8971799638,
"Museum2":34420.9643422388,
"Museum3":826.467789130732,
"Museum4":304120.342151219]
for (k,v) in (Array(d).sorted {$0.1 < $1.1}) {
println("\(k):\(v)")
}
Result:
Museum3:826.467789130732
Museum1:8785.8971799638
Museum2:34420.9643422388
Museum4:304120.342151219
If you think that's wrong, you need to explain why.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With