我想问一些有关核心数据获取过程的问题。我在下面使用Core Data中的fetch方法,但我还需要其他方法。让我向你解释。我试图获取所有数据并将其全部过滤到字典中,但是它不起作用并且对我来说没有意义 我有很多数据,例如
Date Price
01.08.2018 400
03.08.2018 600
04.08.2018 800
06.09.2018 1000
11.09.2018 300
19.09.2018 200
我想获取这些数据,例如:
2018年8月1800 2018年9月1500
我该如何实现?
这是我的提取方法
func fetchLessons() -> [Lessons] {
let context = persistentContainer.viewContext
let fetchRequest = NSFetchRequest<Lessons>(entityName: "Lessons")
do {
let lessons = try context.fetch(fetchRequest)
return lessons
} catch let fetchErr {
print("Failed to fetch students:", fetchErr)
return []
}
}
答案 0 :(得分:1)
如果您要像示例中那样在以数字作为值的字典上使用reduce,请这样做
let sum = dict.reduce(0, { total, item in
total + item.value
})
更新
如果要按月分组,则可以使用简单的for循环进行
var sumPerMonth: [String: Double] = [:]
let formatter = DateFormatter()
formatter.dateFormat = "yyyy MMM"
for item in dict {
let month = formatter.string(from: item.key)
if let value = sumPerMonth[month] {
sumPerMonth[month] = value + item.value
} else {
sumPerMonth[month] = item.value
}
}