0

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 Answer 1

0

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)}
Sign up to request clarification or add additional context in comments.

1 Comment

This is great! I tried to use .map but I left the [ ]... thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.