Here is my scenario: I have a swift WebSocket server and a Javascript client. Over this same WebSocket I will be sending various objects that correspond to different Codable types. It is simple enough to decode if the correct type is known. The difficulty for me is to identify which type is being sent from the client. My first thought was to use JSON that looks like the following:
{type: "GeoMarker",
data: {id: "2",
latitude: "-97.32432"
longitude: "14.35436"}
}
This way I would know to decode data
using let marker = try decoder.decode(GeoMarker.self)
This seems to be straightforward, but for some reason, I just can't figure out how to extract the data
object as JSON so that I can decode it using the GeoMarker type.
Another solution that I came up with was to create an intermediate type like so:
struct Communication: Decodable {
let message: String?
let markers: [GeoMarker]?
let layers: [GeoLayer]?
}
This way I would could send JSON with the following format:
{message: "This is a message",
markers: [{id: "2",
latitude: "-97.32432"
longitude: "14.35436"},
{id: "3",
latitude: "-67.32432"
longitude: "71.35436"}]
}
and use let com = try decoder.decode(Communication.self)
and unwrap the optional message, markers, and layers variables. This works, but seems clunky, especially if I need more types. I will likely end up needing 8-10 after all is said and done.
I have thought through this, but don't feel like I have come up with a satisfactory solution. Would there be better approaches? Is there a standard for this kind of thing that I am unaware of?
----EDIT----
As a natural follow up, how would you go about encoding to that same JSON format, given the same circumstances above?