【问题标题】:Sort Dictionary by Key (Date)按键(日期)排序字典
【发布时间】:2020-06-09 17:40:36
【问题描述】:

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

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

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

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

【问题讨论】:

  • Dictionarys 不倾向于排序 - 这与它们的工作方式背道而驰。相反,您可以将keys 排序到一个单独的数组中,并使用它来查找关联的条目

标签: ios swift sorting dictionary


【解决方案1】:

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

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

然后例如将 tableView 的 dataSource 中的这些排序键用作部分

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()
    }

希望这个例子可以帮助到你

【讨论】:

    【解决方案2】:

    字典根据定义是无序的。

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

    【讨论】:

    • .map(Section.init)
    【解决方案3】:
    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 会引用第一个结构

    【讨论】:

      猜你喜欢
      • 2016-07-24
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 2011-06-17
      相关资源
      最近更新 更多