Skip to content

Instantly share code, notes, and snippets.

@unnamedd
Forked from ElegyD/Sequence+GroupByDate.swift
Created October 26, 2018 17:05
Show Gist options
  • Save unnamedd/a149175d6c869192141ca4cd31c26dfe to your computer and use it in GitHub Desktop.
Save unnamedd/a149175d6c869192141ca4cd31c26dfe to your computer and use it in GitHub Desktop.
Group a Swift Model by date with auto sorting and asc/desc support (Swift 3) E.g.: for a UITableView with sections
extension Sequence {
func groupSort(ascending: Bool = true, byDate dateKey: (Iterator.Element) -> Date) -> [[Iterator.Element]] {
var categories: [[Iterator.Element]] = []
for element in self {
let key = dateKey(element)
guard let dayIndex = categories.index(where: { $0.contains(where: { Calendar.current.isDate(dateKey($0), inSameDayAs: key) }) }) else {
guard let nextIndex = categories.index(where: { $0.contains(where: { dateKey($0).compare(key) == (ascending ? .orderedDescending : .orderedAscending) }) }) else {
categories.append([element])
continue
}
categories.insert([element], at: nextIndex)
continue
}
guard let nextIndex = categories[dayIndex].index(where: { dateKey($0).compare(key) == (ascending ? .orderedDescending : .orderedAscending) }) else {
categories[dayIndex].append(element)
continue
}
categories[dayIndex].insert(element, at: nextIndex)
}
return categories
}
}
/*
Usage:
class Model {
let date: Date!
let anotherProperty: String!
init(date: Date, _ anotherProperty: String) {
self.date = date
self.anotherProperty = anotherProperty
}
}
let modelArray = [
Model(date: Date(), anotherProperty: "Original Date"),
Model(date: Date().addingTimeInterval(86400), anotherProperty: "+1 day"),
Model(date: Date().addingTimeInterval(172800), anotherProperty: "+2 days"),
Model(date: Date().addingTimeInterval(86401), anotherProperty: "+1 day & +1 second"),
Model(date: Date().addingTimeInterval(172801), anotherProperty: "+2 days & +1 second"),
Model(date: Date().addingTimeInterval(86400), anotherProperty: "+1 day"),
Model(date: Date().addingTimeInterval(172800), anotherProperty: "+2 days")
]
let groupSorted = modelArray.groupSort(byDate: { $0.date })
print(groupSorted) // [["Original Date"], ["+1 day", "+1 day", "+1 day & +1 second"], ["+2 days", "+2 days", "+2 days & +1 second"]]
let groupSortedDesc = modelArray.groupSort(ascending: false, byDate: { $0.date })
print(groupSortedDesc) // [["+2 days & +1 second", "+2 days", "+2 days"], ["+1 day & +1 second", "+1 day", "+1 day"], ["Original Date"]]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment