如何使用键(字符串)和结果(NSFetchRequestResult)定义 SectionedFetchResults 的扩展

How to define extension for SectionedFetchResults with Key (String) and Result (NSFetchRequestResult)

我有 SectionedFetchResults 定义如下:

private var consumption: SectionedFetchResults<String?, MedicationConsumption>

MedicationConsumption 的数量可变。我需要为消费编写扩展,它将具有函数 totalQuantity。我尝试了各种方法来扩展它,但没有任何运气。

如何在 SectionedFetchResults 上写扩展,它将 return totalQuantity??

第一个不工作的分机:

extension SectionedFetchResults where Result == NSManagedObject {
    var totalQuantity: Int { /* Code here */ }
}

未编译的第二个扩展:

extension SectionedFetchResults<String, NSFetchRequestResult>.Element {
    var totalQuantity: Int { /* Code here */ }
}

源代码:

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)")
        }
    }
}

药物消耗: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?
}

我想它可以像

  1. 响应的总计:
extension SectionedFetchResults where Result == MedicationConsumption {
    var totalQuantity: Double {
        self.reduce(0) { sum, section in
            section.reduce(into: sum) { [=10=] += .quantity }
        }
    }
}
  1. 部分总计
extension SectionedFetchResults.Section where Result == MedicationConsumption {
    var totalQuantity: Double {
        self.reduce(0) { [=11=] + .quantity }
    }
}

Tested module in project