1

Trying to get into developing with SwiftUI, I went through the Landmarks tutorial and now am trying to apply what I learned for my own example.

I implemented a simple list list-detail view combination and now wanted to also add a delete option. This works fine when deleting after just accessing the list. But if I accessed the detail view of the item to be deleted first, then the app crashes encountering a nil in the detailed view.

The code is as follows (I tried to show relevant parts, but let me know if I possibly should provide more information).

List View

struct ShopprList: View {
    @EnvironmentObject var modelData: ModelData

    var shopprItems: [ShopprItem] {
        modelData.shopprItems
    }
    
    var body: some View {
        NavigationView {
            List {
                ForEach(shopprItems) { shopprItem in
                    NavigationLink(destination: Detail(shopprItem: shopprItem)) {
                        ShopprRow(shopprItem: shopprItem)
                    }
                }
                .onDelete(perform: delete)
            }
            .navigationTitle("Shopping List")
        }
    }
    
    func delete(at offsets: IndexSet) {
        modelData.shopprItems.remove(atOffsets: offsets)
    }
}

And the Detail view is as follows

struct Detail: View {
    @EnvironmentObject var modelData: ModelData
    var shopprItem: ShopprItem
    
    var shopprItemIndex: Int {
        //the following line crashes following the delete with shopprItem being nil, I suppose
        modelData.shopprItems.firstIndex(where: { $0.id == shopprItem.id })!
    }
...

ModelData contains the shopprItems as @Published object

final class ModelData: ObservableObject {
    @Published var shopprItems: [ShopprItem] = load("dummyData.json")
}
...

I feel, like there is some cleanup code missing when leaving the detail view or when executing the delete to mark the item as deleted, but didn't find anything regarding this in the documentation.

To be noted, that the data is not (yet) persisted, I am currently initialising the app with a static set of items from a json script. Persistence will be the next step.

Any hints would be greatly appreciated.

a1x42
  • 11
  • 4

0 Answers0