swift 3.1 如何汇总异步获取属性
Posted
技术标签:
【中文标题】swift 3.1 如何汇总异步获取属性【英文标题】:swift 3.1 How to sum async fetch properties 【发布时间】:2017-03-21 09:57:02 【问题描述】:我无法计算异步提取中单个属性的计数,我想汇总给定异步提取的所有费用金额,但无法按模式申请
我的实体:
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 中调用了这个函数,我如何选择并汇总所有获取的实体的费用金额?
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)")
【问题讨论】:
【参考方案1】:将Expenses
数组映射到expenseAmount
值并将它们相加。
let sum = Expenses.map($0.expenseAmount).reduce(0, $0 + $1)
PS:根据 Swift 3 命名理念,我建议将 Expense
属性命名为 amount
、date
、owner
和 tag
,并删除冗余部分,因为很明显这些属性属于Expense
.
【讨论】:
感谢您的帮助,我在 self.expenseTableView.reloadData() 之后添加了您的字符串并且正在工作,但是您能澄清一下 reduce 的使用吗?reduce
声明一个起始值(0),将数组中的所有项相加并返回总和。以上是关于swift 3.1 如何汇总异步获取属性的主要内容,如果未能解决你的问题,请参考以下文章
Swift 3.1:自定义错误转换为 NSError 以访问其域属性时崩溃
如何在 Swift 中获取 CoreData 属性的“预期”类型?