2017-03-21 30 views
1

我不能MACE在異步單一屬性的計數取,我想薩姆所有expenseAmount對於給定的異步讀取,但在模式不能申請SWIFT 3.1如何總結異步讀取性能

我的實體:

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? 

} 

在我的視圖控制器我把這個FUNC在我viewDidLoad中,我怎麼會選擇和薩姆的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)") 
    } 



} 

回答

0

地圖的Expenses陣列到expenseAmount值並總結它們。

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

PS:根據斯威夫特3命名的理念,我建議命名Expense性質只是amountdateownertag並去除多餘的部分,因爲很明顯,性質屬於Expense

+0

感謝您的幫助,我在self.expenseTableView.reloadData()後添加了字符串並且正在工作,但是您能否澄清reduce的用法? – biggreentree

+0

'reduce'聲明一個起始值(0),添加數組中的所有項目並返回總和。 – vadian