Home > Back-end >  How to define extension for SectionedFetchResults with Key (String) and Result (NSFetchRequestResult
How to define extension for SectionedFetchResults with Key (String) and Result (NSFetchRequestResult

Time:05-24

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?
}

CodePudding user response:

I assume it can be like

  1. for Grand Total for response:
extension SectionedFetchResults where Result == MedicationConsumption {
    var totalQuantity: Double {
        self.reduce(0) { sum, section in
            section.reduce(into: sum) { $0  = $1.quantity }
        }
    }
}
  1. for total in Section
extension SectionedFetchResults.Section where Result == MedicationConsumption {
    var totalQuantity: Double {
        self.reduce(0) { $0   $1.quantity }
    }
}

Tested module in project

  • Related