I have a dictionary, [String : Double]
with the following data:
Museum1 : 8785.8971799638
Museum2 : 34420.9643422388
Museum3 : 826.467789130732
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.
In Swift 2.2, this works
for (k,v) in (Array(d).sort {$0.1 < $1.1}) {
print("\(k):\(v)")
}
Swift 3, it also works:
for (k,v) in (Array(yourDictionary).sorted {$0.1 < $1.1}) {
print("\(k):\(v)")
}
Simple solution for Swift 4 and above...
let dict = ["Museum1":8785.8971799638,
"Museum2":34420.9643422388,
"Museum3":826.467789130732,
"Museum4":304120.342151219]
let dictSortByValue = dict.sorted(by: {$0.value < $1.value} )
for item in dictSortByValue {
print("\(item.key) \(item.value) ")
}
// Museum3 826.467789130732
// Museum1 8785.8971799638
// Museum2 34420.9643422388
// Museum4 304120.342151219
Apparently you can sort a Dictionary in Swift 4--no need to transform into an Array.