I'm struggling to write a single function that encodes the following struct:
struct Lookup: Encodable {
var id: Int
var name: String
enum StateCodingKeys: String, CodingKey {
case id = "stateId"
case name = "stateName"
}
enum CityCodingKeys: String, CodingKey {
case id = "cityId"
case name = "cityName"
}
func encode(to encoder: Encoder, type: StateCodingKeys.Type) throws {
var container = encoder.container(keyedBy: type)
try container.encode(id, forKey: .id)
try container.encode(name, forKey: .name)
}
}
the custom encode function here takes StateCodingKeys.Type as a parameter, but I can't find a way to let this function accept any CodingKey type, like the CityCodingKeys enum, is there a way to do that ?
encode(to:)method that is not shown? Because the generatedEncodableconformance is not going to call yourencode(to:type:)method.lookUpObj.encode(to:type:)when I encode the objectlookupObjEncodable, and I would argue that you should not.