Can't find a way to correct call decode
method with reflected class type. Got ambiguous reference
error on it.
class EntityTwo: Decodable {
var name: String = ""
}
class EntityOne: Decodable {
var value: String = ""
}
struct Entity: Decodable {
var entity: String
var payload: Any
enum CodingKeys: String, CodingKey {
case entity
case payload
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
entity = try container.decode(String.self, forKey: .entity)
let entityType = NSClassFromString("MyFramework." + entity) as! Decodable.Type
payload = try container.decode(entityType, forKey: .payload)
}
}
In background it used to receive different entities from socket:
{
"entity": "EntityOne",
"payload": {
"value": "EntityOneValue"
}
}
{
"entity": "EntityTwo",
"payload": {
"name": "EntityTwoName"
}
}
public func websocketMessage(data: Data) {
let entity = JSONDecoder().decode(Entity.self, from: data)
...
}
Aucun commentaire:
Enregistrer un commentaire