How can I delete an item from array with a button in SwiftUI?

Viewed 600
List{
    ForEach(files, id:\.self){ file in
        HStack{
            Text((file.path as NSString).lastPathComponent)
            Button(action: files.remove(at:files.firstIndex(of: file)!), label: {
                Text("Delete")
            })
        }
    }
}

I have a view with a list in it that shows all the files user chose to process. I need to delete the corresponding file from the array when the button on the list is clicked. Right now its giving me the error "Cannot convert value of type 'URL' to expected argument type '() -> Void'". How can I fix it?

1 Answers

The button action will be wrap with a brackets. As already @EmilioPelaez already mention on the comment. Here is the implemented code.

Button(action: {
        files.remove(at:files.firstIndex(of: file)!)
    }, label: {
        Text("Delete")
 })
Related