【问题标题】:How to fetch as group from Core Data with Swift如何使用 Swift 从 Core Data 中获取分组
【发布时间】:2019-02-05 02:58:51
【问题描述】:

我想让你问一些关于核心数据获取过程的问题。我在下面的 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 []
    }
}

【问题讨论】:

标签: ios swift core-data


【解决方案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
    }
}

【讨论】:

  • 好的,这有助于汇总所有字典结果,但我需要根据相关月份进行汇总。那是我卡住的时候。因此,如果您可以再次检查问题示例数据,您就会明白我的意思
  • @KemalEkren,我错过了,但我已经更新了我的答案
猜你喜欢
  • 2019-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-15
  • 2017-11-11
  • 1970-01-01
相关资源
最近更新 更多