Search code examples
iosasynchronouscore-dataswift3nsfetchrequest

swift 3.1 How to sum async fetch properties


I cannot mace a count of a single property in an asynchronous fetch, I'd like to summ all expenseAmount for given async fetch but cannot apply for in pattern

my entity:

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?

}

in my view controller I call this func in my viewDidLoad, how could I select and summ the expenseAmount values for all fetched entities?

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



}

Solution

  • Map the Expenses array to the expenseAmount values and sum them up.

    let sum = Expenses.map({$0.expenseAmount}).reduce(0, {$0 + $1})
    

    PS: According to the Swift 3 naming philosophy I recommend to name the Expense properties just amount, date, owner and tag and remove the redundant parts since it's clear that the properties belong to Expense .