Reputation: 131
I have a Dictionary. Each key is a date in the format of "dd-mm-yyyy"". The values are arrays of objects. I would like to sort the dictionary by date so that when I display each date as a section in a table view they are in chronological order.
let sortedDict = self?.entriesDict.sorted(by: { $0.key > $1.key })
I think the above could possibly work if I reversed the date format however it is not returning a swift Dictionary (I think it is returning an NSDictionary).
Upvotes: 0
Views: 82
Reputation: 54755
A Dictionary
is an unsorted collection by definition (an NSDictionary
too). If you call sorted
on a Dictionary
, the return value will be of type Array<(Key,Value)>
, an array of the key-value pairs in your dictionary represented as tuples.
To achieve your goals and use a Dictionary
as a UITableViewDataSource
, what you should do is keep a sorted array of your dictionary keys and in your data source methods, retrieve the correct key from that sorted array, then use the key to retrieve the value from the original dictionary.
I'd also suggest storing the dictionary keys as Date
objects rather than date strings.
Without more context in your question, this is roughly what you should do:
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
}
Upvotes: 1