I am trying to write a struct for dynamic data. The keys of the data are unknown as are their values. The struct looks like so:
enum EntryData: Codable {
case string(String)
case array([EntryData]
case nested([String: EntryData])
}
struct Entry: Codable {
var data: [String: EntryData]
}
The goal of this is to be able to decode JSON like this:
{
"data": {
"testA": "valueA",
"testB": ["valueB", ["valueC"]],
"testC": {
"testD": "valueD",
"testE": ["valueE", "valueF"]
}
}
}
And having the following code:
var data = EntryData(data: [
"testA": .string("valueA"),
"testB": .array([.string("valueB"), .array([.string("valueC")])]),
"testC": .nested([
"testD": .string("valueD"),
"testeE": .array([.string("valueE"), .string("valueF")])
])
])
Encode in to the above JSON output.
Is this possible in Swift? If so, how would an implementation look like?
Many thanks in advance.