Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Dictionary by values in Swift

Tags:

swift

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) 
like image 724
NikeAlive Avatar asked Jun 06 '14 20:06

NikeAlive


People also ask

How do you sort a dictionary by value in Swift?

Swift Dictionary sorted() The sorted() method sorts a dictionary by key or value in a specific order (ascending or descending).

How do you sort a dictionary by using values?

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.

Is Swift dictionary ordered?

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.


1 Answers

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 } 
like image 145
S.S.D Avatar answered Oct 01 '22 10:10

S.S.D