Swift 4 Decodable:如何将多个值映射到单个枚举值?

时间:2018-03-29 21:59:52

标签: swift swift4 codable decodable

所以我尝试使用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实现此目的?谢谢!

2 个答案:

答案 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恤,牛仔裤等),所以如果你想要的话,请使用它。