SwiftUI EXC_BAD_INSTRUCTION 过滤和映射数组时

SwiftUI EXC_BAD_INSTRUCTION when filtering and mapping Array

我有一个名为 Lessons 的实体,它包括:

@NSManaged public var timeMinutes: Double
@NSManaged public var id: UUID
@NSManaged public var lessonDescription: String
@NSManaged public var date: Dates

'date' 属性通过一对多关系链接到单独的 'Dates' 实体,该实体包括:

@NSManaged public var date: Date

我现在正在尝试显示一个图表,该图表的总和为 'timeMinutes' 'date'。此 finalArray 将具有以下结构:

struct FinalArray {
    let summedMinutes : Double
    let date : Date
}

我生成(和显示)这个数组的代码如下所示:

import SwiftUI
import SwiftUICharts

struct Test: View {
    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(fetchRequest: Lessons.allLessonsFetchRequest()) var lessons: FetchedResults<Lessons>

   var finalArray = [FinalArray]()

    init(){
        let allKeys = Set<Date>(lessons{[=14=].date.date})
        for key in allKeys {
            let sum = lessons.filter({[=14=].date.date == key}).map({[=14=].timeMinutes}).reduce(0, +)
            finalArray.append(FinalArray(summedMinutes:sum, date:key))
        }
       finalArray = finalArray.sorted(by: {[=14=].date < .date})
    }

    var body: some View {
        VStack{
               LineView(data:  finalArray.map {[=14=].summedMinutes}, title: "This graph returns empty").padding()
               LineView(data:  lessons.map {[=14=].timeMinutes}, title: "This graph works").padding()
        }
    }
}

我在 init 的第一行收到以下错误:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

有谁知道我该如何解决这个问题?这是什么原因?

如果我在我的视图中对核心数据执行 ForEach,它工作正常:

var dateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter
}

        ForEach(lessons.map {[=16=].date.date}, id: \.self) { item in
            VStack{
                Text("\(item, formatter: self.dateFormatter)")
            Text(String(self.lessons.filter{[=16=].date.date == item}.map {[=16=].timeMinutes}.reduce(0, +)))
            }
        }

此代码有效,但这不是我想要的,我想在数组中显示求和的 'timeMinutes'。非常欢迎任何想法或解决方法!

lessons 是在视图初始更新时获取的,但在 init 上尚未定义,因此尝试在那里使用它会发生崩溃。

以下是可能的方法:

   @State private var finalArray = [FinalArray]()

    var body: some View {
        VStack{
               LineView(data:  finalArray.map {[=10=].summedMinutes}, title: "This graph returns empty").padding()
               LineView(data:  lessons.map {[=10=].timeMinutes}, title: "This graph works").padding()
        }
        .onAppear {
           let allKeys = Set<Date>(lessons{[=10=].date.date})
           for key in allKeys {
               let sum = lessons.filter({[=10=].date.date == key}).map({[=10=].timeMinutes}).reduce(0, +)
               finalArray.append(FinalArray(summedMinutes:sum, date:key))
           }
          finalArray = finalArray.sorted(by: {[=10=].date < .date})
       }
    }