This question is about how to write Encodable definition for a custom nested struct I have. I have defined a JSON request struct as follows:
//Define type of request - get or set
enum ReqType: String, Codable {
case get,set
}
//For get request, define what request we can make
enum GetReq: String, Codable {
case getPage,getOther
}
//Request structure - reqBody for now is set to GetReq type
// to keep it simple, no sum type over GetReq and SetReq for now
struct Req {
var reqType: ReqType
var reqBody: GetReq
enum CodingKeys: String, CodingKey{
case reqType
}
}
//An incomplete attempt at encoding logic
extension Req: Encodable {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(reqBody, forKey: .reqType)
}
}
Now, given a request say Req(reqType: ReqType.get,reqBody: GetReq.getPage), we want to encode it as {"get":"getPage"}. That is, key is the string value of ReqType enum, and value is the string value of GetReq enum. My code above can't encode string value of ReqType enum as key. So, it ends up encoding as {"reqType":"getPage"}.
Will appreciate help with fixing the code to achieve the encoding where the key is string value of the enum.