I have a SwiftData @Model that contains a struct which contains an array. Why do I get the following runtime error when I fetch the model and access the struct?
Could not cast value of type '_NSInlineData' (0x11d856fe0) to 'NSArray' (0x1dabccb60).
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
var body: some View {
Text("SwiftData array in struct decoding issue")
.onAppear(perform: addItem)
}
private func addItem() {
let lead1 = Person(skills: [])
let project1 = Project(lead: lead1)
let _ = project1.lead // Runtime error!
}
}
@Model
final class Project {
var lead: Person
init(lead: Person) {
self.lead = lead
}
}
struct Person: Codable {
let skills: [String]
}
Related information:
- It does not matter whether the array is empty or not.
- It also happens with an Int array.
- It also happens with a Set.
- However, an array of a custom struct decodes fine for me and so do dictionaries.
- If you change
let skillstovar skillsthe error becomes "Could not cast value of type '__NSCFData' (0x122862d40) to 'NSArray' (0x1dabcd470)". Be sure to delete the database first. - I cannot make
Persona@Modelbecause it comes from a library and needs to beSendable. - Tested with macOS 14.0 and Xcode 15.0.
let _ = project1.leadbefore theinsertand it should crash for the same reason.init(from decoder:)withlet data = try container.decode(Data.self, forKey: .skills); self.skills = try JSONDecoder().decode([String].self, from: data)it works... Strange though...#Predicateis limited, true. Unfortunate but understandable. But why does decoding fail here outside a predicate? I think your workaround shouldn't be needed.