繁体   English   中英

如何使用Swift从Core Data获取组

[英]How to fetch as group from Core Data with Swift

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

如果要像示例中那样在以数字作为值的字典上使用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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM