[SwiftUI] Deleting from a List of embedded objects, while sorting

I hope I’m not overlooking an answer to this elsewhere:

Given the following Object:

class Person: Object, ObjectKeyIdentifiable {
  @Persisted(primaryKey: true) var _id: ObjectId
  @Persisted var dogs: List<Dog>
}

class Dog: EmbeddedObject {
  @Persisted var name: String
  @Persisted var birthday: Date = Date()
}

I want to display the list of dogs of a person on their details page, sorted by birthdate, like this:

struct PersonView: View {
  @ObservedRealmObject var person: Person

  var body: some View {
    List {
      ForEach(person.dogs.sorted(by: \.birthdate, ascending: false), id: \.self) { dog in
        Text(dog.name)
      }
    }
  }
}

What is the proper way to add onDelete to the ForEach in this scenario?

In my understanding I can’t simply add .onDelete(person.dogs.remove) since person.dogs could be sorted differently, deleting the wrong dog, no? Using .onDelete(person.dogs.sorted(...).remove gives me a “The compiler is unable to type-check this expression in reasonable time”.

The only solution I could come up with was this:

ForEach() {}.onDelete(delete(at:))

func delete(at offsets: IndexSet) {
  offsets.forEach { index in
      // find the dog in the sorted list by index
      if let dog = person.dogs.sorted(by: \.birthday, ascending: false)[safe: index] {
          // get that dogs index in the unsorted embedded list
          if let realIndex = person.dogs.firstIndex(of: dog) {
              $person.dogs.remove(at: realIndex)
          }
      }
  }
}

which works, but that really can’t be it…

1 Like