[英]Sort a Dictionary where the keys are date strings
我有一本字典。 每個鍵都是“dd-mm-yyyy”格式的日期。值是對象數組。我想按日期對字典進行排序,以便當我將每個日期顯示為表視圖中的一個部分時,它們是按年代順序。
let sortedDict = self?.entriesDict.sorted(by: { $0.key > $1.key })
我認為如果我顛倒日期格式,上面的內容可能會起作用,但是它沒有返回一個快速的字典(我認為它正在返回一個 NSDictionary)。
根據定義, Dictionary
是未排序的集合(也是NSDictionary
)。 如果您在Dictionary
上調用sorted
,則返回值的類型將為Array<(Key,Value)>
,即字典中以元組表示的鍵值對數組。
為了實現您的目標並使用Dictionary
作為UITableViewDataSource
,您應該做的是保留字典鍵的排序數組,並在數據源方法中,從該排序數組中檢索正確的鍵,然后使用該鍵從中檢索值原始字典。
我還建議將字典鍵存儲為Date
對象而不是日期字符串。
在您的問題中沒有更多上下文,這大致是您應該做的:
let sortedKeys = entriesDict.keys.sorted()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sortedKeys.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellId", for: indexPath)
let entryKey = sortedKeys[indexPath.row]
cell.textLabel?.text = entriesDict[entryKey]
return cell
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.