I'm trying to setup a SwiftData model with a property whose type is an enum with an associated value. The code works if the enum has no associated value.
Here's a simple model that demonstrates the issue:
@Model
final class Something {
var name: String
var thing: Something.Whatever
init() {
self.name = ""
self.thing = Something.Whatever.a
}
enum Whatever: Codable, Hashable {
case a
case b(Int)
}
}
Here's code that demonstrates the crash:
final class SwiftDataPlayTests: XCTestCase {
var container: ModelContainer!
var schema: Schema!
var modelContext: ModelContext!
override func setUpWithError() throws {
schema = SwiftData.Schema([
Something.self,
])
container = try ModelContainer(for: schema, configurations: [.init(inMemory: true)])
modelContext = ModelContext(container)
}
func testExample() throws {
let item = Something()
let x = item.thing // <== crashes here
print(x)
}
}
The crash is happening in the generated code for the thing
property:
var thing: Something.Whatever
{
init(newValue) accesses (_$backingData) {
self.setValue(for: \.thing, to: newValue)
}
get {
_$observationRegistrar.access(self, keyPath: \.thing)
return self.getValue(for: \.thing) // <== crash here
}
set {
_$observationRegistrar.withMutation(of: self, keyPath: \.thing) {
self.setValue(for: \.thing, to: newValue)
}
}
}
The underlying error is:
SwiftData/BackingData.swift:211: Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(SwiftDataPlayTests.Something.Whatever, Swift.DecodingError.Context(codingPath: [], debugDescription: "Invalid number of keys found, expected one.", underlyingError: nil))
Note that this is happening for any value assigned to the property. item.thing = .a
or item.thing == .b(42)
both give the same error on the let x = item.thing
line.
Are enums with associated values supposed to be supported with SwiftData? If so, what do I need to change in my code to make this work? I'm currently using Xcode 15.0 beta 3.