考虑以下简单的 JSON:
{
"title": "Some title",
"subtitle": "Some subtitle",
"button_type": "rounded"
}
这是我当前解码 ButtonType 字段的方法:
// I dont have access to this enums implementation as it comes from a 3rd party lib.
enum ButtonType {
case squared
case simple
case rounded
case normal
}
struct ResponseModel: Decodable {
var title: String
var subtitle: String
var type: ButtonType
enum CodingKeys: String, CodingKey {
case title = "title"
case subtitle = "subtitle"
case type = "button_type"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
title = try container.decode(String.self, forKey: .title)
subtitle = try container.decode(String.self, forKey: .subtitle)
let stringType = try container.decode(String.self, forKey: .type)
switch stringType {
case "squared":
type = .squared
case "simple":
type = .simple
case "rounded":
type = .rounded
default:
type = .normal
}
}
}
有没有更漂亮的方法来完成将字符串解码为自定义枚举,而无需在纯字符串上迭代令人讨厌的 switch 语句?遗憾的是,我无法访问枚举实现,因为它来自第三方库。如果我这样做,我会让枚举符合 String 和 Codable 并让 Codable 发挥其魔力,但我不这么做。
谢谢!
您可以创建自己的
enum
enum MyButtonType: String {
case squared
case simple
case rounded
case normal
var toButtonType: ButtonType {
switch self {
case .squared: return .squared
case .simple: return .simple
case .rounded: return .rounded
case .normal: return .normal
}
}
}