Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift sort dictionary by value

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?

like image 214
user986690 Avatar asked Dec 05 '22 23:12

user986690


1 Answers

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.

like image 85
matt Avatar answered Dec 29 '22 22:12

matt