SwiftUI从ForEach中删除绑定数组元素

SwiftUI从ForEach中删除绑定数组元素,swiftui,swift5,Swiftui,Swift5,即使在阅读了多篇关于这个主题的文章之后,我也不知道如何从for each数组中删除绑定元素。正如我在其他一些SO答案中所建议的那样,我使用了这个指南来创建一个可以传递给子视图的数据数组。具体地说,observeObject和ObservedObject部分的更新3 我有一个视图模型,其中包含从CoreData class PathsViewModel:NSObject,ObservableObject{ @Published var recordedPaths:[UUID: UserPa

即使在阅读了多篇关于这个主题的文章之后,我也不知道如何从for each数组中删除绑定元素。正如我在其他一些SO答案中所建议的那样,我使用了这个指南来创建一个可以传递给子视图的数据数组。具体地说,
observeObject
ObservedObject
部分的
更新3

我有一个视图模型,其中包含从
CoreData

class PathsViewModel:NSObject,ObservableObject{
    @Published var recordedPaths:[UUID: UserPath] = [:]
    @Published var recordedPathIdentifiers:[UUID] = []
这些值为每个值填充一个值,如下所示:

ForEach(pathsVM.recordedPathIdentifiers, id:\.self){ id in
    PathCell(pathInformation: $pathsVM.recordedPaths[unchecked: id])
onDelete
方法定义为:

    func performDelete(at indexes:IndexSet){
        indexes.forEach{ idx in
            pathsVM.deletePath(index: idx)
        }
        pathsVM.getUserPaths()
    }

    func deletePath(index:Int){
        let deletionId = recordedPathIdentifiers.remove(at: index)
        
        let toDelete = CoreDataManager.shared.getPathById(recordedPaths[unchecked: deletionId].internalID)
        CoreDataManager.shared.viewContext.delete(toDelete)
        CoreDataManager.shared.save()
    }
路径单元格包含如下数据。注意:有些人建议这样做,以便PathCell不观察pathInformation,但我的路径单元格也有按钮来切换单元格的开关,因此我需要该功能

//Shows an individual path cell's information.
struct PathCell:View{
    @EnvironmentObject var settingsVM:SettingsViewModel
    @EnvironmentObject var pathsVM:PathsViewModel
    
    @Binding var pathInformation:UserPath
    @State private var isShowingPathDetail:Bool = false
经过数小时的调试,我发现当我删除列表时,应用程序崩溃了。不知何故,
ForEach
正在访问一个
UUID
,该UUID已从
recordedpath
recordedPathIdentifiers
中删除

如果您能帮助我理解为什么这不起作用,以及如何正确地修复它,我将不胜感激

编辑: 经过一系列的检查,问题似乎是
PathCell
(它是
PathView
的子视图)有一个名为
pathInformation
的绑定,当数据被删除时,
PathCell
视图在
PathView
之前被更新,因此ForEach仍然有一个包含旧信息的
PathCell
,它现在正试图显示已删除信息的内容

我相当肯定,这就是问题所在,但我真的不明白如何才能解决这个问题