首页 > 解决方案 > 按键(日期)排序字典

问题描述

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

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

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

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

标签: iosswiftsortingdictionary

解决方案


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

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

希望这个例子可以帮助你


推荐阅读