繁体   English   中英

按键(日期)对字典排序

[英]Sort Dictionary by Key (Date)

我正在创建一个需要按日期分组的笔记列表,并按该日期排序显示它们。 对于支持这一点的数据结构,我有一个这样的字典:

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

我试过使用sortedDictionary.sorted { $0.0 < $1.0 }但它返回一个元组而不是一个字典。

如果有人可以就我如何将该元组变异回字典或仅使用日期键对字典进行排序提供一些帮助,将不胜感激。

是的,字典根据定义是无序的,但是您可以创建一个字典键的排序数组

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

然后例如在 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()
    }

希望这个例子可以帮助你

根据定义,字典是无序的。

您可以将字典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

顺便说一句:字典顺序不可靠

来自 Swift 的字典文档:

字典中键值对的顺序在突变之间是稳定的,但在其他方面是不可预测的。 如果您需要键值对的有序集合并且不需要 Dictionary 提供的快速键查找,请参阅 KeyValuePairs 类型以获取替代方法。

此外,Swift 结构会被保留,除非它们的内部值发生变化,重新排序会维护这些值,当您将重新排序的 dict 分配给其他 var/let 时,swift 将引用第一个结构

暂无
暂无

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

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