<分区>
编译器提示:“枚举大小写的原始值必须是文字”
在结构/类中我们可以使用泛型值,但如何在enum
中使用泛型。
下面是我想做一个通用结构的服务器响应
{
"status": true,
"message": "message",
"error" : "error if any"
"any key" : "Any kind of data"
}
在上面的例子中,“任意键”部分是棘手的。对于不同的服务调用,“任意键”会有所不同。
对于用户城市列表:
{
"status": true,
"message": "message",
"error" : ""
"cities" : "city list"
}
对于用户状态列表:
{
"status": true,
"message": "message",
"error" : ""
"states" : "state list"
}
对于用户帖子:
{
"status": true,
"message": "message",
"error" : ""
"posts" : "list of posts"
}
您可以看到每个服务调用都有相同的键“状态”、“消息”和“错误”,数据有不同的键“城市”、“州”、“帖子”等.
所以我想创建一个通用结构,将所有这些都包含在一个结构中。
我按照以下方式做了,但卡在了不同的键上。
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)
}
}
这可能是我正在尝试做的事情吗?
如果是,如何实现?
任何帮助将不胜感激!!
我在尝试时遇到了以下错误......
Raw value for enum case must be a literal
Non-nominal type 'T' does not support explicit initialization