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 ?
You can create a common protocol for both of your enums, add the enum cases you need as
static vars, and conform the enums to the protocol.Then you can add the protocol as a generic constraint:
Side note:
If you just want to call
encode(to:type:)directly to encode aLookup, I would suggest that you do not conform toEncodable, sinceLookupwould have a generatedencode(to:)method, that does not call yourencode(to:type:).When you accidentally pass
Lookupto something that expects anEncodable, and that something encodes it usingencode(to:), it will have the unexpected keysidandname.I haven't tried, but you might be able to conform to
EncodableWithConfigurationinstead, with the configuration being the type of the coding key.