I am using coredata.
Draw a rectangle by taking only 2 values with ForEach. However, when I add new data or modify the data, the app crashes.
ForEach must have a maximum index value of 1. This is because the limit of fetchrequest is 2. However, when I add new data, the value of index becomes 2 and get an 'out of range' error.
I've been looking for an answer for 16 hours.
import SwiftUI
struct chart: View{
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest var datas: FetchedResults<Mind>
@State var show = [true, false]
init() {
let request: NSFetchRequest<Success> = Mind.fetchRequest()
request.sortDescriptors = [
NSSortDescriptor(keyPath: \Success.date, ascending: false)
]
request.fetchLimit = 2
_datas = FetchRequest(fetchRequest: request)
}
var body: some View{
VStack(alignment: .leading){
ForEach(0..<datas.map{$0.suc}.count, id: \.self){ index in
RoundedRectangle(cornerRadius: 5)
.fill(Color.objcolor.opacity(show[index] ? 1 : 0.7))
.frame(width: 10, height: 5)
}
}
}
}