Parsing Server Response with Codable SwiftletModel Entities
Related: iOS App Development, SwiftletModel
That's the most straightforward SwiftletModel use case.
SwiftletModel relations are Codable. Entity Models implemented with SwiftletModel can be plain structs.
It means that we can get Codability for free:
@EntityModel
struct Message: Codable {
let id: String
let text: String
@Relationship(.required)
var author: User?
@Relationship(.required, inverse: \.messages)
var chat: Chat?
@Relationship(inverse: \.message)
var attachment: Attachment?
@Relationship(inverse: \.replyTo)
var replies: [Message]?
@Relationship(inverse: \.replies)
var replyTo: Message?
@Relationship
var viewedBy: [User]? = nil
}
Benefits of using SwiftletModel for parsing Codable JSON response:
- Support of nested models with recursion
- Lossless decoding
- Incomplete data handling
Nested Models SwiftletModel supports recursive nested models which can be beneficial when parsing weirdly shaped JSON structs.
Lossless decoding Backend API can be out of our control and it can be inconsistent. Lossless decoding strategy enables a more reliable way to handle it compared to using Codable struct directly.
Incomplete Data Handling SwiftletModel provides a strategy to handle incomplete data for several use cases: incomplete entity model data, and incomplete related models and relations. This serves the goal of protecting the model graph from inconsistency.
Read more about [[how SwiftletModel handles incomplete data]].
Comments