swift 3.1 如何总结异步获取属性

swift 3.1 How to sum async fetch properties

我无法在异步获取中对单个 属性 进行计数,我想对给定异步获取的所有费用金额求和,但无法在模式中申请

我的实体:

extension Expense {

@nonobjc public class func fetchRequest() -> NSFetchRequest<Expense> {
    return NSFetchRequest<Expense>(entityName: "Expense");
}

@NSManaged public var expenseAmount: Double
@NSManaged public var expenseDate: NSDate?
@NSManaged public var expenseOwner: String?
@NSManaged public var expenseTag: String?

}

在我的视图控制器中,我在我的 viewDidLoad 中调用了这个函数,我怎么能select并对所有获取的实体的 expenseAmount 值求和?

func makeAsyncFetch() {


    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return
    }
    managedContext = appDelegate.persistentContainer.viewContext


    // MARK: - async fetch request 2
    let expenseFetch = NSFetchRequest<Expense>(entityName: kExpenseEntityName)

    asyncFetchRequest = NSAsynchronousFetchRequest<Expense>(fetchRequest: expenseFetch) {
        [unowned self] (result: NSAsynchronousFetchResult) in
        guard let Expenses = result.finalResult else {
            return
        }
        self.asyncExpensesArray = Expenses
        self.expenseTableView.reloadData()
        //            self.testPrintForMyArray(arrayToCheck: self.asyncExpensesArray)
        //            self.batchUpdate()
    }
    // MARK: - async fetch request 3
    do {
        try managedContext.execute(asyncFetchRequest)
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }



}

Expenses 数组映射到 expenseAmount 值并将它们相加。

let sum = Expenses.map({[=10=].expenseAmount}).reduce(0, {[=10=] + })

PS:根据 Swift 3 命名理念,我建议将 Expense 属性命名为 amountdateownertag 并删除冗余部分,因为很明显这些属性属于 Expense .