是否可以按日期desc或asc排序分组数组?
我正在从JSON Web服务中提取日记约会列表,并按日期将它们分组。分组工作良好(我将集合视图的补充视图中的约会日期用作标题),并且所有约会均正确显示在其各自的标题中,但是日期都乱了?
我的代码如下:
do {
if !self.appointments.isEmpty {
self.appointments.removeAll()
}
if !self.groupedAppointments.isEmpty {
self.groupedAppointments.removeAll()
}
self.appointments = try JSONDecoder().decode([DiaryAppointment].self, from: data!)
let groupedDictionary = Dictionary(grouping: self.appointments) { (appointment) -> String in
return appointment.appointmentDate!
}
let keys = groupedDictionary.keys.sorted()
keys.forEach({
self.groupedAppointments.append(groupedDictionary[$0]!)
})
self.diaryList.reloadData()
completionHandler(success, nil)
} catch let error {
print("This went wrong", error)
completionHandler(success, error)
}
....
func numberOfSections(in collectionView: UICollectionView) -> Int {
return groupedAppointments.count > 0 ? groupedAppointments.count : 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if groupedAppointments.count > 0 {
return groupedAppointments[section].count
}
return appointments.count
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if let sectionHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerID, for: indexPath) as? SectionHeader {
if !self.groupedAppointments.isEmpty {
sectionHeader.headerLabel.text = self.groupedAppointments[indexPath.section][indexPath.row].appointmentDate
}
return sectionHeader
}
return UICollectionReusableView()
}
以上内容为我提供了正确的部分数量,在标题中显示了正确的日期,在部分中显示了正确的单元格。但是这些部分没有按日期排序。
答案 0 :(得分:1)
appointmentDate
是String
类型,转换为日期,然后您就可以使用ComparisonResult
groupedDictionary.keys.sorted(by: {$0.compare($1) == .orderedDescending })