如何使用具有自定义初始值设定项的枚举类型值的解码结构中的值?

How to use the value from a decoded struct that has an enum type value with custom initializers?

我有一个 API 响应 returns 一个 JSON 类型不一致的字段。因此,我去 https://www.quicktype.io 寻求帮助并找到了一个模型。

这是我遇到问题的模型部分:

struct MyModel: Codable {
    let id: ID?
}

enum ID: Codable {
    case integer(Int)
    case string(String)

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if let x = try? container.decode(Int.self) {
            self = .integer(x)
            return
        }
        if let x = try? container.decode(String.self) {
            self = .string(x)
            return
        }
        throw DecodingError.typeMismatch(ID.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for ID"))
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .integer(let x):
            try container.encode(x)
        case .string(let x):
            try container.encode(x)
        }
    }
}

我有一个完全解码的响应,当我尝试打印该值时,我得到类似:

Optional(MyApp.ID.integer(27681250))

Optional(MyApp.ID.string(27681250))

我这样做是通过:

print(modelData?.id)

我想访问我得到的确切值,但我无法这样做。 我试过将它转换为其他类型,但没有帮助。 任何帮助表示赞赏。谢谢。

您可以通过多种不同的方式执行此操作。所有这些都在 The Swift Programming Language book in the Enumerations 部分进行了解释。

这只是其中一种方法...

func example(id: ID) {
    switch id {
    case let .integer(value):
        <#code#>
    case let .string(value):
        <#code#>
    }
}