Context.insert() but at index 0

Hello!

I am an inexperienced programmer learning swiftUI and swiftData so apologies in advance if this answer can be found elsewhere.

I want to display a list of recent transcriptions, stored in modelContainer, in reversed order. I attempted to do transcriptionsList.reversed() in a ForEach (which is in a swiftUI List), but .onDelete gets messed up as it is deleting the items as per the normal order.

The question is, is there a way when using context.insert(), that I can specify to insert at index 0? Or is there a better way of resolving this?

Thanks in advance!

The code when pasted in here appears to not be formatted correctly so I didn't include code

As far as I know, SwiftData doesn't necessarily save/query everything in the order in which they were created. So if you want to put a new object at a certain place in the list you don't know for sure if it will be saved nonetheless queried in the order you specify.

A better way of approching this would be to sort the list when you query your data. If you want to sort your list by creation time, I would add a new Date attribute to your model and add a SortDescriptor to your Query.

Like this:

@Model
final class Transcription {
    var text: String
    var creationDate: Date
    
    init(text: String, creationDate: Date) {
        self.text = text
        self.creationDate = creationDate
    }
}

struct ContentView: View {
    @Environment(\.modelContext) var context
    @Query(sort: \Transcription.creationDate, order: .reverse) var transcriptions: [Transcription]

    var body: some View {
        List {
            ForEach(transcriptions) { transcription in
                Text(transcription.creationDate.formatted(date: .abbreviated, time: .standard))
            }
            .onDelete { indexSet in
                for index in indexSet {
                    context.delete(transcriptions[index])
                }
            }
            
            Button("Add new transcription") {
                context.insert(Transcription(text: "", creationDate: .now))
            }
        }
    }
}

#Preview {
    ContentView()
        .modelContainer(for: Transcription.self, inMemory: true)
}
Context.insert() but at index 0
 
 
Q