SwiftData error "Thread 1: Fatal error: Composite Coder only supports Keyed Container"

I'm using SwiftData to store data in my app and I recently had to store both image data and colors.

I have therefore added two variables to my model, one of type Data? and the other of type Color.Resolved?

If both are set to nil then I can call context.save() without any error but when providing a value of type Color.Resolved, the following error message occurs: Thread 1: Fatal error: Composite Coder only supports Keyed Container.

Any guidance on how to solve this and what needs to be done to store image data and colors with SwiftData?

Answered by joadan in 813364022

If you create a Color.Resolved value in a playground and encodes it you see you get an array of doubles rather than a structure with RGB properties and the error clearly states that an array (keyless container) is not supported.

So I guess the conclusion is that Color.Resolved isn't supported by SwiftData.

My playground test code and output

let color = Color.red
var resolvedColor: Color.Resolved
resolvedColor = color.resolve(in: EnvironmentValues())

let data = try! JSONEncoder().encode(resolvedColor)
print(String(data: data, encoding: .utf8)!) 

[1,0.23137254,0.18823528,1]

Accepted Answer

If you create a Color.Resolved value in a playground and encodes it you see you get an array of doubles rather than a structure with RGB properties and the error clearly states that an array (keyless container) is not supported.

So I guess the conclusion is that Color.Resolved isn't supported by SwiftData.

My playground test code and output

let color = Color.red
var resolvedColor: Color.Resolved
resolvedColor = color.resolve(in: EnvironmentValues())

let data = try! JSONEncoder().encode(resolvedColor)
print(String(data: data, encoding: .utf8)!) 

[1,0.23137254,0.18823528,1]

SwiftData error "Thread 1: Fatal error: Composite Coder only supports Keyed Container"
 
 
Q