SwiftUI: How to handle list item deletion with a dynamic data source?
I'm currently working on a SwiftUI app where I need to manage a list of items that can be dynamically added and removed. The items are fetched from a remote server, and I'm using a `@State` variable to hold the fetched data. However, I'm running into issues when trying to delete an item from the list. After calling the deletion method, the app crashes with a 'Index out of range' behavior. Here's a simplified version of my code: ```swift struct Item: Identifiable { let id: UUID let name: String } struct ContentView: View { @State private var items: [Item] = [] var body: some View { List { ForEach(items) { item in Text(item.name) } .onDelete(perform: deleteItem) } } func deleteItem(at offsets: IndexSet) { offsets.map { items[$0] }.forEach { item in // Assuming 'removeItemFromServer' is a method that removes the item from the remote server removeItemFromServer(item) } // This line is what causes the crash items.remove(atOffsets: offsets) } func removeItemFromServer(_ item: Item) { // Simulating a network request to remove the item, but it might throw an behavior or take time } } ``` I've tried ensuring that the item removal from the server is completing before I update the `items` array, but the question continues. I also considered using a completion handler for `removeItemFromServer`, but I'm not sure how to implement that effectively with SwiftUI. Any advice on how to manage the state correctly here to avoid the 'Index out of range' behavior would be greatly appreciated. Also, are there best practices for handling asynchronous operations in SwiftUI when deleting items from a list?