Search code examples
swiftuiswiftui-list

SwiftUI / iOS app crashing when I delete a row with alternating .listRowBackground colors


I have alternating colors set for my list with: .listRowBackground((self.restaurants.firstIndex(of: restaurant)! % 2 == 0) ? Color.myLightGray: Color.white), but when I delete a row, program crashes and returns the following error: Fatal error: Unexpectedly found nil while unwrapping an Optional value

If I remove the .listRowBackground line in the code, the program runs fine when I delete a row in the list, but of course I don't get alternating colors.

I appreciate any help in solving this error.

        List {
            ForEach(restaurants) { restaurant in
                
                NavigationLink(value: restaurant) {
                    VStack {
                        HStack {
                            let uiimage = UIImage(data: restaurant.photo)
                            Image(uiImage: uiimage ?? UIImage(imageLiteralResourceName: "pepper"))
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                                .frame(maxWidth: 40, maxHeight: .infinity)
                                .clipShape(Circle())
                                .padding(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
                            Text(restaurant.location)
                            Spacer()
                            EmojiRatingView(rating: restaurant.mainGrade)
                            
                                .font(.system(size: 12))
                                .foregroundColor(.red)
                        }
                    }.frame(height: 36)

                }
                .listRowBackground((self.restaurants.firstIndex(of: restaurant)! % 2 == 0) ? Color.myLightGray: Color.white)

            }.onDelete(perform: deleteRestaurants)

        }


func deleteRestaurants(at offsets: IndexSet) {
        for offset in offsets {
            let restaurant = restaurants[offset]
            modelContext.delete(restaurant)
        }
    }

Solution

  • This is expected behavior, you're forcing unwrap by (self.restaurants.firstIndex(of: restaurant)!. Try to provide a default value if it is nil instead of forcing it like this.

    .listRowBackground(
        (restaurant.firstIndex(of: restaurant) ?? 0) % 2 == 0 ? Color.myLightGray: Color.white
    )