Is there are analog of - (NSArray *)keysSortedByValueUsingSelector:(SEL)comparator in swift?
How to do this without casting to NSDictionary?
I tried this, but it seems to be not a good solution.
var values = Array(dict.values) values.sort({ $0 > $1 }) for number in values { for (key, value) in dict { if value == number { println(key + " : \(value)"); dict.removeValueForKey(key); break } } }
Example:
var dict = ["cola" : 10, "fanta" : 12, "sprite" : 8] dict.sortedKeysByValues(>) // fanta (12), cola(10), sprite(8)
Swift Dictionary sorted() The sorted() method sorts a dictionary by key or value in a specific order (ascending or descending).
First, we use the sorted() function to order the values of the dictionary. We then loop through the sorted values, finding the keys for each value. We add these keys-value pairs in the sorted order into a new dictionary. Note: Sorting does not allow you to re-order the dictionary in-place.
There is no order. Dictionaries in Swift are an unordered collection type. The order in which the values will be returned cannot be determined. If you need an ordered collection of values, I recommend using an array.
Just one line code to sort dictionary by Values in Swift 4, 4.2 and Swift 5:
let sortedByValueDictionary = myDictionary.sorted { $0.1 < $1.1 }
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