0

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 []
    }
}
Esat kemal Ekren
  • 516
  • 2
  • 8
  • 28
  • Possible duplicate of [How do I use an SQL GROUP BY and SUM functions in a IOS CORE-DATA request in SWIFT?](https://stackoverflow.com/questions/28010110/how-do-i-use-an-sql-group-by-and-sum-functions-in-a-ios-core-data-request-in-swi) – Joakim Danielson Aug 30 '18 at 08:28
  • let me check it quick Thanks in advance – Esat kemal Ekren Aug 30 '18 at 08:29
  • Group the data into a dictionary like suggested in your [previous question](https://stackoverflow.com/questions/52043162/how-can-i-group-fetched-dates-by-month) – the suggestions do work – and use `reduce` to sum up date values. It's pretty easy and efficient. – vadian Aug 30 '18 at 08:30
  • @vadian Thank you for showing me to path I fetch my data as dictionary as I shared in the below – Esat kemal Ekren Aug 30 '18 at 15:58
  • @vadian Here is My dictionary [2018-03-28 20:47:30 +0000: 750.0, 2018-08-28 20:47:44 +0000: 1500.0] – Esat kemal Ekren Aug 30 '18 at 15:59
  • @vadian I can group that like previous question but i couldn't use reduce function could you help me out? – Esat kemal Ekren Aug 30 '18 at 15:59
  • @JoakimDanielson I did try that answer but not worked – Esat kemal Ekren Aug 30 '18 at 16:00

1 Answers1

1

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
    }
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52