简体   繁体   English

按键(日期)对字典排序

[英]Sort Dictionary by Key (Date)

I'm creating a list of notes that I need to group by date and the display them sorted by that date.我正在创建一个需要按日期分组的笔记列表,并按该日期排序显示它们。 For the data structure to support this I have a dictionary like this:对于支持这一点的数据结构,我有一个这样的字典:

var sortedDictionary: [Date: [String]] = [:]

I've tried using sortedDictionary.sorted { $0.0 < $1.0 } but that returns a tuple and not a dictionary.我试过使用sortedDictionary.sorted { $0.0 < $1.0 }但它返回一个元组而不是一个字典。

If anyone could provide some help on how I can either mutate that tuple back into a dictionary or just sort the dictionary using the keys which are dates it would be much appreciated.如果有人可以就我如何将该元组变异回字典或仅使用日期键对字典进行排序提供一些帮助,将不胜感激。

Yeah dictionaries are unordered by definition, but you could create a sorted array of dictionary keys是的,字典根据定义是无序的,但是您可以创建一个字典键的排序数组

let dict: [Date: [String]] = [:]
let sortedKeys = dict.keys.sorted { $0 < $1 }

and then eg use these sorted keys in the tableView's dataSource as a section然后例如在 tableView 的数据源中使用这些排序的键作为一个部分

extension NotesViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return sortedKeys.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dict[sortedKeys[section]]?.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let value = dict[sortedKeys[indexPath.section]]?[indexPath.row] 
            else { return UITableViewCell() }

        return UITableViewCell()
    }

Hope this example could help you希望这个例子可以帮助你

Dictionaries are unordered by definition.根据定义,字典是无序的。

You could map the dictionary to a (array of) struct which can be sorted您可以将字典map到可以排序的(数组)结构

struct Section {
    let date : Date
    let notes : [String]
}

let sections = groupedDictionary.map{Section(date: $0.key, notes: $0.value}.sorted{$0.date < $1.date}
let whatYouGet: [Dictionary<Date, [String]>.Element] = unsortedDictionary
                                                         .sorted { $0.0 < $1.0 }
whatYouGet.forEach { print("\($0.key): \($0.value)") } // you search this

BTW: Dictionary orders are not reliables顺便说一句:字典顺序不可靠

From Swift's Dictionary Documentation:来自 Swift 的字典文档:

The order of key-value pairs in a dictionary is stable between mutations but is otherwise unpredictable.字典中键值对的顺序在突变之间是稳定的,但在其他方面是不可预测的。 If you need an ordered collection of key-value pairs and don't need the fast key lookup that Dictionary provides, see the KeyValuePairs type for an alternative.如果您需要键值对的有序集合并且不需要 Dictionary 提供的快速键查找,请参阅 KeyValuePairs 类型以获取替代方法。

In addition, Swift structs are retained unless their internal values change, an reorder maintains these values, when you assign the reorder dict to other var/let, swift give the reference to first struct此外,Swift 结构会被保留,除非它们的内部值发生变化,重新排序会维护这些值,当您将重新排序的 dict 分配给其他 var/let 时,swift 将引用第一个结构

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

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