简体   繁体   中英

Sorting dictionary keys based on a value of the tuple associated with the key in swift

I currently have a dictionary of type [String: (Int, NSDate)] . I would like to get an array of the keys (which are the strings in this case) sorted by the NSDate which is in the tuple.

So far, the best I could obtain is this code:

var ret = sorted(self.dictionary, {
  var tuple1 = $0.1 as (Int, NSDate)
  var tuple2 = $1.1 as (Int, NSDate)
  return tuple1.1.compare(tuple2.1) == NSComparisonResult.OrderedAscending
})

But that returns something of the following type: [(String, (Int, NSDate)) ]

Is there an easy way for me to retrieve an array of strings only?

ret = sorted(self.dictionary, ...) returns an array of (key,value) tuples. You can extract the keys with

let keys = map(ret) { $0.0 }

Alternatively, sort the keys based on their values in the dictionary:

let keys = sorted(self.dictionary.keys) {
    (key1, key2) in
    let tuple1 = self.dictionary[key1]!
    let tuple2 = self.dictionary[key2]!
    return tuple1.1.compare(tuple2.1) == NSComparisonResult.OrderedAscending
}

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