I have a small example where adding a new property to a persisted Codable struct causes a crash on launch instead of decoding the missing property using its default value.
Steps
Run this app once and press "Insert Event" to persist data:
import SwiftUI
import SwiftData
@main
struct SwiftDataCrash: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: Event.self)
}
}
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var events: [Event]
var body: some View {
VStack(spacing: 12) {
Text("Events: \(events.count)")
Button("Insert Event") {
let event = Event(
recurrence: Recurrence(
interval: 1
)
)
modelContext.insert(event)
try? modelContext.save()
}
List(events) { event in
Text(String(describing: event.recurrence))
}
}
.padding()
}
}
@Model
final class Event {
var recurrence: Recurrence? = nil
init(recurrence: Recurrence? = nil) {
self.recurrence = recurrence
}
}
struct Recurrence: Codable {
var interval: Int
// STEP 2:
// After first run + inserting an Event, uncomment this and run again.
// Expected: old data decodes with default []
// Actual: SwiftData may crash while reading Event.recurrence
//
// var exceptionDates: [Date] = []
}
Then uncomment:
var exceptionDates: [Date] = []
and run again without deleting the store.
Actual result
App crashes on launch with:
Could not cast value of type 'Swift.Optional<Any>' to 'Swift.Array<Foundation.Date>'
The crash appears to happen inside generated SwiftData persisted-property getter code.
Expected result
I expected the old persisted Recurrence values to decode with:
exceptionDates == []
Is this expected behavior or a SwiftData bug?
0
0
25