swiftswiftuinsindexset

How to access the array position using SwiftUI's onDelete() function


I am attempting to sync the UI delete with deleting a record from CloudKit. SwiftUI has the onDelete() function that you can add to a List view which gives you the swipe to delete gesture. I am trying to use this to access the position in the array of the deleted item so I can refer to it in another function to handle the deletion from Cloud Kit. Here is how SwiftUI sets up onDelete().

List {
    ForEach(recordsHandler.audioRecords) { record in
        Button(action: {
            //set the showModal variable to true to show DetailModalView
            self.showModal = true
            self.recordToPass = record
        }) {
            AudioRowView(audio: record)
     }
     .sheet(isPresented: self.$showModal) {
         PlaybackModalView(selectedRecord: self.recordToPass).environmentObject(self.recordsHandler)
     }
}
.onDelete(perform: delete)

Below is my custom row view. Doesn't really add much to the problem but in case it does.

struct AudioRowView: View {

    var audio: Audio

    var body: some View {
        HStack {
            Text(audio.title)
                .padding(5)
            Spacer()
            Text(audio.type)
                .padding(10)
                .background(Color.black)
                .foregroundColor(Color.white)
                .cornerRadius(20)
        }
        .frame(height: 50)
    }
}

And below is the delete function at present which as is, provides the swipe gesture and deletes the entry from the list view. As stated I am now trying to decipher what position in the array the row was and so I can call it in another function and proceed with deleting the entry from CloudKit.

func delete(at offsets: IndexSet) {
    recordsHandler.audioRecords.remove(atOffsets: offsets)
}

Solution

  • As you are given the offsets, so you can tell one by one:

     func delete(at offsets: IndexSet) {
    recordsHandler.audioRecords.remove(atOffsets: offsets)
        for row in offsets{
            print(row)}
    }