我有两个数组:
var sections: [SectionContent] = []
var cells: [CellContent] = []
在这两个数组中,一个嵌套在另一个里面:
struct SectionContent {
let sectionDate: Date
let sectionContent: [CellContent]
}
struct CellContent {
let cellDate: Date?
var formattedDate: String {
guard let text = cellDate else { return "" }
return DateFormatter.stringDate.string(from: text)
}
}
extension DateFormatter {
static let stringDate: DateFormatter = {
let formatterDate = DateFormatter()
formatterDate.dateFormat = "MMM d, h:mm a"
return formatterDate
}()
}
'sections'数组将日期显示为tableView中的节标题。
“单元格”数组显示分配给该日期的相应数据。
日期是在一个单独的viewController中设置的,我从该viewController中对第一个viewController执行unwindSegue操作。
我设法通过在unwindSegue中包含以下代码来按日期对各部分进行排序:
sections.sort { $0.sectionDate < $1.sectionDate }
问:给定我的配置,如何按相应的时间(较早的时间在顶部,较晚的时间在底部)对一个部分中的单元格进行排序?
编辑:这是我如何构建部分:
func sortByDate() {
sections.removeAll()
let dates = cells.reduce(into: Set<Date>()) { result, cells in
let date = Calendar.current.startOfDay(for: cells.cellDate!)
result.insert(date) }
for date in dates {
let dateComp = Calendar.current.dateComponents([.year, .month, .day], from: date)
var sortedContent: [CellContent] = []
cells.forEach { cells in
let contComp = Calendar.current.dateComponents([.year, .month, .day], from: cells.cellDate!)
if contComp == dateComp {
sortedContent.append(cells) } }
let newSection = SectionContent(sectionDate: date, sectionContent: sortedContent)
sections.append(newSection) } }
2条答案
按热度按时间yjghlzjz1#
只给予未排序/已排序的部分交给此函数,它将返回已排序的部分
icomxhvb2#
按您正在执行的顺序对这些部分进行排序
然后按下面的方式排序
请注意,必须将
sectionContent
更改为var,第二次排序才能起作用