Skip to content

Instantly share code, notes, and snippets.

@beechtom
Last active October 5, 2023 07:44
Show Gist options
  • Save beechtom/43dd79b1c70dfcbe947e1886a97051e1 to your computer and use it in GitHub Desktop.
Save beechtom/43dd79b1c70dfcbe947e1886a97051e1 to your computer and use it in GitHub Desktop.
SectionedResults-08
import SwiftData
struct SectionedResults<SectionIdentifier, Result>: RandomAccessCollection
where SectionIdentifier: Hashable, Result: PersistentModel {
typealias Element = Self.Section
typealias Index = Int
typealias Iterator = IndexingIterator<Self>
var elements: [Element]
var startIndex: Index = 0
var endIndex: Index { elements.count }
subscript(position: Index) -> Element {
elements[position]
}
init(sectionIdentifier: KeyPath<Result, SectionIdentifier>,
results: [Result]) {
let groupedResults = Dictionary(grouping: results) { result in
result[keyPath: sectionIdentifier]
}
let identifiers = results.map { result in
result[keyPath: sectionIdentifier]
}.uniqued()
self.elements = identifiers.compactMap { identifier in
guard let elements = groupedResults[identifier] else { return nil }
return Section(id: identifier, elements: elements)
}
}
struct Section: RandomAccessCollection, Identifiable {
typealias Element = Result
typealias ID = SectionIdentifier
typealias Index = Int
typealias Iterator = IndexingIterator<Self>
var id: ID
var elements: [Element]
var startIndex: Index = 0
var endIndex: Index { elements.count }
subscript(position: Index) -> Element {
elements[position]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment