'How to delete entries from sorted SwiftUi RealmData

Update: I will provide more detailed. I hope my issue is getting clearer now :)

I am using Realm to store exercises. These exercises containing progress:

    final class Exercise: Object, ObjectKeyIdentifiable {
        @Persisted(primaryKey:  true) var _id: ObjectId
        //...
            
        @Persisted var progress: RealmSwift.List<Progress>
        
        //...
        }
    }
    
    final class Progress: Object, ObjectKeyIdentifiable {
        @Persisted(primaryKey:  true) var _id: ObjectId
        
        @Persisted var date: Date
        
        @Persisted var weight: Double
        
        @Persisted(originProperty: "progress") var group: LinkingObjects<Exercise>
    }

I want to manage the progress in a SwiftUi-View. Cause the data is unsorted I want to display this data ordered by date.


    ForEach(exercise.progress.sorted(byKeyPath: "date", ascending: false)) { progress in
                            Text(progress.date, style: .date)
    ...
                        }
                        .onDelete(perform: $exercise.progress.remove)

When I try to delete a progress entry from the list (and the same time from the database), the wrong entry might be deleted.

It looks like the index of the SwiftUI-ForEach-List is not the same as the internal data list index.

So my updated question is: Is this a normal behaviour and if so how can I "sync" the index of a visual-list with a realmswift-list?

Thnx Alex



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source