0
votes

I am trying to use a fetch request in a SwiftUI Charts package/CocoaPod. My issue is that when I use a ForEach to iterate over the Attribute (ACFTScores.totalScore) it populates one value per chart... I know this is because the BarChart is in the body of the ForEach but I don't know how to grab the range of the fetch and make it work with the SwiftUI Charts.

enter image description here

struct DashboardACFT: View {
    @FetchRequest(entity: ACFTScores.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \ACFTScores.totalScore, ascending: true)]) var acftScores: FetchedResults<ACFTScores>

    var body: some View {
        VStack {
            ForEach(acftScores, id: \.id) { score in
                BarChartView(data: [Int(score.totalScore)], title: "Title", legend: "Legendary")
            }
        }
    }
}
1

1 Answers

0
votes

I haven't worked with charts but you need to map your fetch request into an array containing the values you want to use in your chart. Something like this

var body: some View {
    VStack {
        BarChartView(data: acftScores.map {$0.totalScore}, title: "Title", legend: "Legendary")
        }
    }
}

Since you for some reason seems to need to convert the property to Int using compactMap might be better.

acftScores.compactMap {Int($0.totalScore)}