Sorting Dictionary in Swift 3

Trying to sort NSMutableDictionary in Swift 3, the code from Swift 2 no longer works for me (various errors).

I am trying to use the following code to sort my dictionary by its values: float:

var sortedDict = unsortedDict.allValues.sorted({ $0 < $1 }).flatMap({ floatedlotterydictionary[$0] }) 

Essentially, I need this unsorted dictionary ...

 { a = "1.7"; b = "0.08"; c = "1.4"; } 

... to include this sorted dictionary ...

 { b = "0.08"; c = "1.4"; a = "1.7"; } 

But using this line of code above returns the error "The argument type anyobject does not match the NSCopying type" for part $0 < $1 . So how can I sort a dictionary by its values ​​in Swift 3?

(Note: This line of code is partially derived from this answer .)

I am using Swift 3 in Xcode 8 beta 1 .

+6
source share
2 answers

Ok The collection methods available in the regular dictionary are still available, but the type of objects is not applied, which adds an insatiable inheritance.

In docs sorted , a closure is performed, which allows us to access the key and the value at the same time and consider it as one element and, therefore, sort the dictionary.

 let k: NSMutableDictionary = ["a" : 1.7, "b" : 0.08, "c" : 1.4] print(k.sorted(isOrderedBefore: { (a, b) in (a.value as! Double) < (b.value as! Double) })) 

Casting is required because the types a.value and b.value AnyObject . This works on my computer, starting up Xcode Version 8.0 beta (8S128d).

+7
source

Also like this:

 let k = ["a" : 1.7, "b" : 0.08, "c" : 1.4] print(k.flatMap({$0}).sort { $0.0.1 < $0.1.1 }) 
+4
source

All Articles