Skip to content

Instantly share code, notes, and snippets.

@beechtom
Created October 5, 2023 07:40
Show Gist options
  • Save beechtom/6fae86681aade9be59aa441d0dc50ad5 to your computer and use it in GitHub Desktop.
Save beechtom/6fae86681aade9be59aa441d0dc50ad5 to your computer and use it in GitHub Desktop.
SectionedResults-10
import SwiftData
struct SectionedResults<SectionIdentifier, Result>: RandomAccessCollection
where SectionIdentifier: Hashable, Result: PersistentModel {
// ...
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)
}
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment