如何使用Swift从Core Data中获取组

问题描述 投票:0回答:1

我想让你问一下Core Data fetch进程。我在下面的核心数据中使用了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月18日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 []
    }
}
ios swift core-data
1个回答
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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.