'How to define extension for SectionedFetchResults with Key (String) and Result (NSFetchRequestResult)
I have SectionedFetchResults defined like this:
private var consumption: SectionedFetchResults<String?, MedicationConsumption>
MedicationConsumption have variable quantity. I need to write extension for consumption that, it will have function totalQuantity. I have tried various way on extending it, but without any luck.
How to write extension on SectionedFetchResults, that it will return totalQuantity??
1st extension which is not working:
extension SectionedFetchResults where Result == NSManagedObject {
var totalQuantity: Int { /* Code here */ }
}
2nd extension which is not compiling:
extension SectionedFetchResults<String, NSFetchRequestResult>.Element {
var totalQuantity: Int { /* Code here */ }
}
Source code:
static var fetchRequest: NSFetchRequest<MedicationConsumption> {
let result = MedicationConsumption.fetchRequest()
result.sortDescriptors = [NSSortDescriptor(keyPath: \MedicationConsumption.date, ascending: true)]
result.predicate = NSPredicate(format: "(medication.type == 1)")
return result
}
@SectionedFetchRequest(fetchRequest: Self.fetchRequest, sectionIdentifier: \MedicationConsumption.group)
private var consumption: SectionedFetchResults<String?, MedicationConsumption>
// Use case scenario
var body: some View {
List(waterConsumption) { section in
VStack {
Text("\(section.totalQuantity)")
}
}
}
MedicationConsumption: NSManagedObject
extension MedicationConsumption {
@nonobjc public class func fetchRequest() -> NSFetchRequest<MedicationConsumption> {
return NSFetchRequest<MedicationConsumption>(entityName: "MedicationConsumption")
}
@NSManaged public var date: Date?
@NSManaged public var group: String?
@NSManaged public var quantity: Double
@NSManaged public var medication: Medication?
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
