Compiler complains: "Raw value for enum case must be a literal"
In the struct/class we can use generic value but how to use generic in enum
.
The below is the server response that I want to make a general structure
{
"status": true,
"message": "message",
"error" : "error if any"
"any key" : "Any kind of data"
}
In above example the "any key" part is tricky one. "any key" will be different for different service call.
for user city list:
{
"status": true,
"message": "message",
"error" : ""
"cities" : "city list"
}
for user state list:
{
"status": true,
"message": "message",
"error" : ""
"states" : "state list"
}
for user posts:
{
"status": true,
"message": "message",
"error" : ""
"posts" : "list of posts"
}
An you can see every service call has same key for "status", "message" and "error" and the data has different keys "cities", "states", "posts", etc.
So I want to create a general struct to include all these in to one.
I did the following way but stuck at different keys.
struct Response<T>: Codable {
let message : String? // common in every service call
let status : Bool? // common in every service call
let errors: String? // common in every service call
let data : T? // it will be different for every call
enum CodingKeys: String, CodingKey {
case message = "message"
case status = "status"
case data = <key> //Here what to use?
case errors = "errors"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
message = try values.decodeIfPresent(String.self, forKey: .message)
status = try values.decodeIfPresent(Bool.self, forKey: .status)
errors = try values.decodeIfPresent(String.self, forKey: .errors)
data = try T(from: decoder)
}
}
Is it possible what I'm trying to do?
If yes, how to achieve this?
Any help will be appreciated!!
I got following errors when I was trying..
Raw value for enum case must be a literal
Non-nominal type 'T' does not support explicit initialization