如何对存储的核心数据的数字(Int16)求和

编程入门 行业动态 更新时间:2024-10-17 13:30:07
如何对存储的核心数据的数字(Int16)求和 - Swift 3(How to sum the numbers(Int16) of stored core data - Swift 3)

我已经在核心数据中存储了字母(String),数字(Int16)和日期(Date)。 过滤器(NSPredicate)成功地只组织了必要的数据。

我想得到这个核心数据中数字的总和。

实体名称:实体 属性名称:字母(字符串),值(Int16),日期(日期)

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 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.

Entity Name : Entity Attribute Name : Letter(String), Value(Int16), Date(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.

最满意答案

您已经获取了记录,因此以这种方式获取Value属性的总和。

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

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)

更多推荐

本文发布于:2023-08-07 01:26:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1458701.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:核心   数字   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!