[英]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.