fatbobman / blogComments

1 stars 0 forks source link

在 SwiftData 模型中使用 Codable 和枚举的注意事项 #248

Open fatbobman opened 1 month ago

fatbobman commented 1 month ago

在 SwiftData 模型中使用 Codable 和枚举的注意事项

相较于 Core Data,SwiftData 在数据模型的构建方式上实现了根本性的革新。它不仅支持纯代码的声明方式,还允许在模型中直接使用符合 Codable 协议的类型及枚举类型,这些都是其显著的新特性。许多开发者都倾向于利用这些新功能,因为它们似乎非常契合 Swift 语言的声明风格。然而,若对这些新功能的实现细节和潜在限制理解不足,开发者可能会在未来遇到不少问题。本文旨在探讨在 SwiftData 模型中使用 Codable 和枚举时需要注意的几个关键点,帮助开发者避免走入误区。

Considerations for Using Codable and Enums in SwiftData Models

Compared to Core Data, SwiftData has fundamentally revolutionized the way data models are constructed. It not only supports a purely code-based declaration method but also allows the direct use of types conforming to the Codable protocol and enum types within models, which are its significant new features. Many developers are inclined to leverage these new capabilities because they seem to fit very well with the Swift language's declaration style. However, a lack of understanding of the implementation details and potential limitations of these new features may lead to various issues in the future. This article aims to discuss several key points to consider when using Codable and enums in SwiftData models, helping developers avoid common pitfalls.

mesqueeb commented 3 weeks ago

This is such a good article! I want to mention my own experience:

Inside the Codable implementation you must use the same property names for your CodingKeys as the properties of the Model. Otherwise SwiftData will not save the property at all!

This is AFAIK undocumented behaviour that cost me 8h to find out 🥲

In my case, I had a property called moves in my Model, and in the Codable implementation I saved the field as movesDict (manually converting my array to a dictionary), but this made it so nor moves nor movesDict was persisted at all! It would always load my SwiftData records with empty data for moves. 😭

I would love some more clarity on dos / donts when it comes to Codable for SwiftData models. I can double check the data being saved via "DB Browser for SQLite" but when looking at the underlying data, I'm never sure if I'm making good or bad choices. 😅

fatbobman commented 3 weeks ago

hi Luca, When writing this article, I considered your previous reminder that names must be consistent. But I did not reproduce this result in a simple model. Perhaps this problem only occurs when the model reaches a certain complexity. I will add this section to the article after I have more information.

mesqueeb commented 3 weeks ago

@fatbobman hi Luca, When writing this article, I considered your previous reminder that names must be consistent. But I did not reproduce this result in a simple model. Perhaps this problem only occurs when the model reaches a certain complexity. I will add this section to the article after I have more information.

Thank you for your comment! I will also try and provide a minimal reproduction in the near future to better help document this. : )