Say I have to send this data to the server:
struct Event: Codable {
let title: String
let params: [String:Any]? //Not allowed
}
So for instance, these events could look like any of these:
let event = Event(title: "cat was pet", params:["age": 7.2])
let event = Event(title: "cat purred", params:["time": 9])
let event = Event(title: "cat drank", params:["water": "salty", "amount": 3.3])
I need the ability to send any arbitrary amount of key/value pairs as params
to the event. Is this even possible with Codable
? If not, how would I encode params
as a json string?
2
Answers
Using a type like JSONValue, it would look almost identical to what you describe:
There’s a lot of helper code in JSONValue, but at its heart is just an enum, as described in Swift/JSONEncoder: Encoding class containing a nested raw JSON object literal:
Everything else is just helpers to encode/decode, conform to
ExpressibleBy...
protocols, etc.Codable
is magic if all types conform toCodable
, but in your case I suggest traditionalJSONSerialization
. Add a computed propertydictionaryRepresentation
then encode the event
This is less expensive/cumbersome than forcing
Any
to becomeCodable
(no offense, Rob).