My app gets its data from an API endpoint.
The data is a Review and the model looks like this:
struct Review: Identifiable, Decodable {
var id: Int
var reviewable_type: String
var score: Int?
var reviewable: <THIS CAN BE A MOVIE, A SHOW OR AN EPISODE>
var user: User
var created_at: String?
var created: String?
var text: String?
}
As you can see the reviewable
property can be of multiple types.
How do I implement this? I have different data models for Movie, Show and Episode.
Note: the reviewable_type holds the value of the type that’s in the reviewable
variable. I don’t know if that helps.
I tried things with protocols and extensions, but can’t seem to get it to work.
2
Answers
I like AntonioWar's answer if the objects all have the same fields, which they don't. Maybe it still works that way but it wasn't clear to me from his answer.
What I did to solve it was this: I created a
Reviewable
struct with all the fields from theShow
,Episode
andMovie
structs:Then, I added this as the type in the
Review
struct:Then, I created extensions for the 3
Reviewable
objects, with a function that converts theReviewable
to theMovie
,Episode
orShow
:Because I know which type it is from the
reviewable_type
variable on theReview
, I can use this to decode it in to the right struct:Maybe it is a very shabby way of doing it but this is what worked for me (and maybe someone else can use it).
What you can do is transform the struct Review into a protocol with an associative type, that is another protocol Reviewable.
This protocol must at least conform to the Decodable protocol, but it can also possibly contain attributes in common between all the contents, such as an ID for example.
The struct Review is transformed like this:
You will then have a struct for each type of reviewable content:
And one struct for each Review Type.
They can then all be used within data structures of type any Review. Here’s a simple example: