简体   繁体   中英

How to fetch as group from Core Data with Swift

I want you to ask something about Core Data fetch process. I am using fetch method in the below from Core Data but I need something else. Let me explain to you. I 've tried to fetch all data and filter all of it in a dictionary but it didn't work and didn't make sense to me I have many data like

    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

I want to fetch these data like:

Aug 2018 1800 September 2018 1500

How can i achieve of that?

Here is my fetch method

 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 []
    }
}

If you want to use reduce on a dictionary that has numbers as values as in your example then do

let sum = dict.reduce(0, { total, item in
    total + item.value
})

Update

If you want to group by month then you can use a simple for loop to do it

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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