ios - 按键(日期)排序字典
问题描述
我正在创建一个需要按日期分组的笔记列表,并按该日期排序显示它们。对于支持这一点的数据结构,我有一个这样的字典:
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()
}
希望这个例子可以帮助你
推荐阅读
- python - 如何在 Python 中实现 OCL(对象约束语言)
- cassandra - 如何在 Cassandra 的另一个 UDT 中嵌套一个 UDT?
- javascript - 在 Qualtrics 中,如何在具有可变 QID 的调查的后期检索答案?
- spring-webflux - Spring reactor - 延迟触发方法,无需等待结果
- python-3.x - Oracle SQLPLUS:监控数据复制进度
- amazon-web-services - Cloudformation 堆栈 UPDATE_ROLLBACK_FAILED 使用 AmazonEC2ContainerServiceFullAccess 更新 IAM 角色策略
- javascript - 我不明白谷歌应用脚本中的这种拼接行为
- python - 使用 python libclang 解析 C++ 宏行(带注释)
- python - 如何使用 Numba 对具有多个输出的函数进行矢量化?
- c# - 从到旋转毛刺我的角色控制器