如何对存储的核心数据的数字(Int16)求和-Swift 3 [英] How to sum the numbers(Int16) of stored core data - Swift 3

查看:76
本文介绍了如何对存储的核心数据的数字(Int16)求和-Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在核心数据中存储了字母(字符串),数字(Int16)和日期(日期)。
并且过滤器(NSPredicate)仅成功组织了必要的数据。

I have stored the letters(String), numbers(Int16) and Date(Date) in the core data. And the filter(NSPredicate) succeeded in organizing only the necessary data.

我想获取此核心数据中数字的总和。

I want to get the total sum of the numbers in this core data.


  • 实体名称:实体

  • 属性名称:Letter(String),Value(Int16),Date(日期)

let context = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext

let entityDesc: NSEntityDescription = NSEntityDescription.entity(forEntityName: "Entity", in: context)!

let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()

request.entity = entityDesc

// Omit date NSFormatter

let dateCheck = formatter.string(from: today)

request.predicate = NSPredicate(format: "Date == %@", dateCheck)

let records = try! context.fetch(request)

我不知道下一步该怎么做。
我是开发的初学者,希望有人能提供帮助。

I do not know what to do next. I am a beginner in development and hope someone can help.

推荐答案

您已经获取了记录,因此获取

You have already fetch the records, so get the sum of the Value attribute this way.

try! context.fetch(request) as! [NSManagedObject]
let sum = result.reduce(0) { $0 + ($1.value(forKey: "Value") as? Int16 ?? 0) }
print(sum)

这篇关于如何对存储的核心数据的数字(Int16)求和-Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆