I’m currently working on a simple read operation based on object IDs using SwiftData in my view model. I’m fetching data like this:
func fetch(ids: [String]) {
var models: [SwiftDataModel] = []
do {
let predicate = #Predicate<SwiftDataModel> {
ids.contains($0.id)
}
let descriptor = FetchDescriptor<SwiftDataModel>(predicate: predicate, sortBy: [SortDescriptor(.title)])
models = try context.fetch(descriptor)
} catch {
return []
}
}
I’m unsure about the predicate part:
let predicate = #Predicate<SwiftDataModel> {
ids.contains($0.id)
}
While this seems logical to me, and I am getting correct results, I’m uncertain if it’s the correct/efficient approach.
I know there is something like this:
if let model = context.model(for: yourIdGoesHere) as? MyModel {}
but is there something similar for fetching multiple objects by their ids?