简体   繁体   中英

Sort swift dictionary by value and then sort the final result by key for keys having the same value

I have a dictionary of [myStruct:Int] which I want to sort first by the value and then second for keys with the same value, i want to sort them by a string attribute 'item' in 'myStruct'

struct myStruct {
    var item: String!
    var amount: Int!
}

I tried to implement the suggestion Swift: Sort dictionary keys by value, then by key , which is an awesome solution IMO, but i cannot implement it for the custom struct I have.

Any help please?

To implement referenced solution with sorting closures, you should define corresponding comparison operator for your structure

func < (lhs: myStruct, rhs: myStruct) -> Bool {
  return lhs.item < rhs.item 
}

Assuming you make your struct hashable so that it can be a key to your dictionary and comparable so that it cna be sorted, you can sort a dictionary by value and key using the following sort parameters:

let dict   = [ "A" : 1, "B" : 2, "C" : 2, "D" : 2, "E" : 1 ]
for (key,value) in dict.sort({ $0.1 == $1.1 ? $0.0 < $1.0 : $0.1 < $1.1 })
{
  print("\(value),\(key)")
}
// prints:
// 1,A
// 1,E
// 2,B
// 2,C
// 2,D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM