onDelete:在条目被删除之前访问条目中的数据

onDelete: Accessing Data From Entry Before it is Deleted

当用户滑动删除列表中的条目时,是否有一个指针可以用来获取有关被删除条目的信息?在删除条目之前,我想知道类别总数。我在使用函数 removeItems 时遇到问题,它给出错误:无法将类型 'IndexSet' 的值转换为预期的参数类型 'Int'

struct CatItem:  Codable, Identifiable {
    var id = UUID()
    var catNum: Int       
    var catName: String
    var catTotal: Double
    var catPix: String
    var catShow: Bool 
}

class Categories: ObservableObject {
    
    @Published var catItem: [CatItem] {
    didSet {
         }
     }
 } 





struct manCatView: View {
    
    @EnvironmentObject var userData: UserData
    @EnvironmentObject var categories: Categories
    
    var pic: String = ""
    
    var body: some View {
        
        List {
            ForEach(0 ..< categories.catItem.count) { index in
                if index.catShow == true {
                HStack {
                    let pic = categories.catItem[index].catPix
                    Image(systemName: pic)
                        .resizable()
                        
                        .foregroundColor(Color(colors[index]))
                        .frame(width: 40, height: 40)
                    
                    Text(categories.catItem[index].catName)
                    }
                }
            }
            .onDelete(perform: removeItems) 
        }
        .navigationBarTitle(Text("Manage Categories"), displayMode: .inline)
        NavigationLink(destination: addCatView()) {Text("Add Categories")
            .fontWeight(.bold)}
            .font(.title2)
            .disabled(categories.catItem.count > 16)
            
            .padding([.leading, .trailing], 10)
            .accentColor(Color(red: 60/255, green: 160/255, blue: 240/255))
        
        Text("")
        Text("")
        Text("Add Up to 5 Categories")
        Text("Swipe Left to Delete a Category")
        
        Rectangle()
            .frame(width: 50, height: 175)
            .foregroundColor(.white)
    }
    
    
    func removeItems(at offsets: IndexSet) {
        var catTotal: Double = 0.0
        
        //subtract entry amount from category total
        catTotal = categories.catItem[offsets].catTotal  // <-- need help with index here
        userData.totalArray[grandTotal] -= catTotal
        userData.totalArray[userTotal] -= catTotal
        
        
        categories.catItem.remove(atOffsets: offsets)
    }
}

这里的IndexSet 是简单的Indexies 集合,在简单的情况下它将只包含一个元素(用户通过滑动一个一个地删除条目)。因此,为简单起见,您可以为此使用 .first 元素。但更好的是 - 遍历整个集合,它会让你有更多的控制权。

因此您需要的代码可能与此类似:

func removeItems(at offsets: IndexSet) {
    var catTotal: Double = 0.0
    
    offsets.forEach { singleOffset in
        //subtract entry amount from category total
        catTotal = categories.catItem[singleOffset].catTotal
        userData.totalArray[grandTotal] -= catTotal
        userData.totalArray[userTotal] -= catTotal
    }
    
    categories.catItem.remove(atOffsets: offsets)
}