The question is this: how do you group Core Data objects by attribute and then perform simple calculations (let's say, sum) on them?
I've found a few similar answers for this (like this one), but none seem conclusive and all are geared up towards Swift (whereas I am working on SwiftUI).
For example, I have a Core Data model that looks like this:
extension Items {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Items> {
return NSFetchRequest<Items>(entityName: "Items")
}
@NSManaged public var id: UUID?
@NSManaged public var cost: Int16
@NSManaged public var type: String
}
In the Home()
view, I'd like to group by type and then find the total amount paid (i.e. sum of cost) for all objects in each type.
So far, I've tried making a special group()
function (a bit like in this question), but get the error message "Cannot find 'i' in scope".
struct Home: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(entity: Items.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Items.type, ascending: true)]) var items: FetchedResults<Items>
var body: some View {
ForEach(group(items), id: \.self) { [i] in
Text("\([i].cost.reduce(0,+))")
}
}
}
func group(_ result : FetchedResults<Items>)-> [[Items]] {
return Dictionary(grouping: result) { $0.type }
.sorted(by: {$0.key < $1.key})
.map {$0.value}
}
Surely this can't be so hard? Any help very welcome!