所以我尝试使用Decodable将字段解码为这种格式:
enum ClothingType: String, Decodable {
case SHIRT
case PANTS
case SHOES
case HAT
}
但我的JSON在引号中返回以下值,我希望它们映射到上述四种类型之一:
"T_SHIRT"
和"LONG_SLEEVE_SHIRT"
- > SHIRT
"JEANS"
和"SHORTS"
- > PANTS
"SNEAKERS"
和"SANDALS"
- > SHOES
"BASEBALL_CAP"
和"WINTER_HAT"
- > HAT
如何使用Decodable实现此目的?谢谢!
答案 0 :(得分:1)
我建议做这样的事情:
enum ClothingType: String, Codable {
case tShirt = "T_SHIRT"
case longSleepShirt = "LONG_SLEEVE_SHIRT"
case jeans = "JEANS"
case shorts = "SHORTS"
case sneakers = "SNEAKERS"
case sandals = "SANDALS"
case baseballCap = "BASEBALL_CAP"
case winterHat = "WINTER_HAT"
var subType: SubType {
switch self {
case .tShirt, .longSleepShirt:
return .shirt
case .jeans, .shorts:
return .pants
case .sneakers, .sandals:
return .shoes
case .baseballCap, .winterHat:
return .hat
}
}
enum SubType {
case shirt
case pants
case shoes
case hat
}
}
它允许您将编码数据结构保持为最终结果,同时允许您保留命名约定并定义哪些方面对您很重要。
答案 1 :(得分:0)
本周我了解到Decodable非常灵活,您可以执行以下操作:
enum ClothingType: Decodable {
case shirt
case pants
case shoes
case hat
private enum RawClothingType: String, Decodable {
case tShirt = "T_SHIRT"
case longSleepShirt = "LONG_SLEEVE_SHIRT"
case jeans = "JEANS"
case shorts = "SHORTS"
case sneakers = "SNEAKERS"
case sandals = "SANDALS"
case baseballCap = "BASEBALL_CAP"
case winterHat = "WINTER_HAT"
}
init(from decoder: Decoder) throws {
let rawClothingType = try RawClothingType(from: decoder)
switch rawClothingType {
case .tShirt, .longSleepShirt: self = .shirt
case .jeans, .shorts: self = .pants
case .sneakers, .sandals: self = .shoes
case .baseballCap, .winterHat: self = .hat
}
}
}
这隐藏了原来的服装类型(T恤,牛仔裤等),所以如果你想要的话,请使用它。