Monday, August 26, 2024

Using Codable and Enums in SwiftData Models

Fatbobman (Reddit):

In SwiftData’s default storage implementation, the method of persisting the people attribute is not by converting data into binary format through encoders such as JSONEncoder and storing it in a single field (similar to Core Data’s Value Transformer). Instead, SwiftData creates separate fields for each attribute of Codable data within the table corresponding to the entity (interpreted as converting to Core Data’s Composite attributes).

[…]

Such errors indicate that not all complex types conforming to the Codable protocol are suitable for SwiftData models. Although some complex Codable types may compile correctly, they can lead to inconsistent behavior and anomalies in practice (many developers have reported such issues without a clear pattern).

It’s odd how Codable is used as the marker for automatic destructuring, but then SwiftData doesn’t actually follow your Codable conformance (or even the CodingKeys names) to decide how to do it.

Due to the non-fully encoding and decoding nature of Codable types, altering their properties by adding, removing, or renaming can disrupt SwiftData’s lightweight data migration mechanism. This is particularly critical when the application employs SwiftData’s built-in cloud synchronization feature, as such modifications may not comply with the cloud synchronization rules, leading to sync failures.

[…]

Although using enum types directly as model properties is highly convenient, as of iOS 18, SwiftData still does not support using enum types as query predicates.

Previously:

Comments RSS · Twitter · Mastodon

Leave a Comment