I'm encountering an issue encoding/decoding a custom struct from SwiftData. As it's all happening behind the generated code of SwiftData and a decoder, I'm not really sure what's going on.
I have a custom type defined kind of like this:
public struct Group<Key: Hashable, Element: Hashable> {
private var elementGroups: [Element: Key]
private var groupedElements: [Key: [Element]]
}
In short, it allows multiple elements (usually a string), to be grouped, referenced by some key.
I have Codable conformance to this object, so I can encode and decode it. For simplicity, the elementGroups
is encoded/decoded, and the groupedElements
is rebuilt when decoding. My implementation is similar to this:
extension Group: Codable where Key: Codable, Element: Codable {
private enum Keys: CodingKey {
case groups
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Keys.self)
let decoded = try container.decode([Element: Key].self, forKey: .groups)
// Enumerate over the element groups, and populate the list of elements.
//
var elements: [Key: [Element]] = [:]
for group in decoded {
elements[group.value] = (elements[group.value] ?? []) + [group.key]
}
elementGroups = decoded
groupedElements = elements
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: Keys.self)
try container.encode(elementGroups, forKey: .groups)
}
}
This works fine when encoding and decoding to JSON, but when I attempt to use this structure as a value within a SwiftData model, then decoding the type crashes my application.
@Model
final class MyModel {
var id: UUID = UUID()
var groups: Group<UUID, String> = Group<UUID, String>()
init(id: UUID) {
self.id = id
}
}
When something attempts to decode the groups property on the MyModel
object, it crashes with the following error:
Could not cast value of type 'Swift.Optional<Any>' (0x1ed7d0290) to 'Swift.Dictionary<Swift.String, Foundation.UUID>' (0x121fa9448).
I would guess that there is a nil value stored for groups in SwiftData, and attempting to decode it to a Group<UUID, String>
type is failing. It's odd that it doesn't throw an exception though, and hard crashes. Also, I'm not sure why it's optional, as a value is being written out.
Does anyone have any ideas?