fatbobman / blogComments

1 stars 0 forks source link

如何处理 SwiftData 谓词中的可选值 #222

Open fatbobman opened 6 months ago

fatbobman commented 6 months ago

如何处理 SwiftData 谓词中的可选值

由于 SwiftData 更改了数据模型的创建机制,而且谓词创建也采用了基于模型代码的类型安全模式。因此,当开发者在为 SwiftData 构建谓词时会遇到大量的处理可选值的操作。本文将探讨在构建谓词时,处理可选值的一些技巧和注意事项。

How to Handle Optional Values in SwiftData Predicates

SwiftData has revamped the mechanism for creating data models, incorporating a type-safe mode for predicate creation based on model code. As a result, developers encounter numerous operations involving optional values when constructing predicates for SwiftData. This article will explore some techniques and considerations for handling optional values while building predicates.

ImaginativeWork commented 6 months ago

What are your thoughts on representing JSON with Core Data, backed by a SQLite database (which can now store data with JSON database functions)?

fatbobman commented 6 months ago

@ImaginativeWork , Although SQLite can directly store JSON data, neither Core Data nor SwiftData currently support using JSON as a property type directly. In Core Data, JSON data is typically stored as binary or string. In SwiftData, if a property type conforms to the Codable protocol, SwiftData attempts to decompose that type into multiple SQLite-supported primitive types, creating corresponding fields for these primitive data types for storage. This means that SwiftData does not convert them into a format like JSON. While it is still not possible to use the decomposed data as a predicate for comparisons, I believe that future versions will likely introduce this capability. This approach is relatively more efficient and flexible than converting and storing data as JSON.

pj-madrid commented 1 month ago

Your examples only work with Strings. To compare other objects using a predicate I made them Identifiable and added "var id: String = UUID().uuidString" to the class and used your examples to compare object.ids. Thank you so much for your clear and concise examples they helped set me on the right track.