I’ve run into a reproducible issue when using SwiftData with @Model classes that contain non-optional value type properties (struct) with optional properties inside.
After creating a new model, the app crashes with:
Fatal error: Passed nil for a non-optional keypath \MyModel.myStruct
This happens immediately after try? modelContext.save() is called.
This is my example:
import SwiftData
import SwiftUI
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query(sort: \MyModel.name) private var models: [MyModel]
@State private var selectedModel: MyModel?
var body: some View {
NavigationStack {
List(models) { model in
Button(model.name) {
selectedModel = model
}
}
.navigationTitle("Models")
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button("Add") {
let newModel = MyModel(name: "Test")
modelContext.insert(newModel)
try? modelContext.save()
selectedModel = newModel
}
}
}
.sheet(item: $selectedModel) { model in
Text("Editing \(model.name)")
}
}
}
}
@Model
class MyModel {
var name: String
var myStruct: MyStruct
init(name: String) {
self.name = name
self.myStruct = MyStruct(value: nil)
}
}
struct MyStruct: Codable {
var value: String?
}
@main
struct MinimalReproApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: MyModel.self)
}
}
If I change the value property in MyStruct so it's no longer an optional, the crash no longer occurs.
I would prefer a solution that ideally does not involve modifying MyStruct.
var myStruct: MyStructit should be optional?. You could just make@Model class MyStructModeland use that instead of a struct.