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)
}
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags: