核心数据@FetchRequest SwiftUI

Core Data @FetchRequest SwiftUI

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.

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

我没有使用过图表,但您需要将提取请求映射到一个数组中,该数组包含您要在图表中使用的值。像这样

var body: some View {
    VStack {
        BarChartView(data: acftScores.map {[=10=].totalScore}, title: "Title", legend: "Legendary")
        }
    }
}

由于某些原因,您似乎需要将 属性 转换为 Int,使用 compactMap 可能更好。

acftScores.compactMap {Int([=11=].totalScore)}