简体   繁体   English

基于与swift中的键相关联的元组的值对字典键进行排序

[英]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)] . 我目前有一个类型为[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. 我想得到一个键的数组(在这种情况下是字符串),由元组中的NSDate排序。

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)) ] 但是返回以下类型的东西: [(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. ret = sorted(self.dictionary, ...)返回的数组 (key,value)元组。 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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