Swift: Enum codable 如何获取原始值

Swift: Enum codable how to get raw value

我有一个class字段类型ID(枚举class),两者都是可编码的,我无法读取枚举的原始值,我应该如何实现其他

我的代码:

struct Answer: Codable {
    let id: ID?
    let message: String?

    enum CodingKeys: String, CodingKey {
        case id = "Id"
        case message = "Message"
    }
}

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)
        }
    }
}

如何读取这样的值answer.id?.rawValue

在声音中我得到的 id 可以是整数或字符串,所以自动使用 class 可编码 swift 知道实例是好的枚举。

所以如果我收到我想要的整数:

answer.id?.rawValue

//output 4

所以如果我收到我想要的字符串:

answer.id?.rawValue

//output "male"

当我打印这个时,我注意到它与一个值相关联:

print(answer.id.debugDescription)
//Output: Optional(fitto.ID.integer(2)) or if is string Optional(fitto.ID.string("female"))

一种解决方案是在枚举中添加两个计算属性以获得关联的值。

var stringValue : String? {
    guard case let .string(value) = self else { return nil }
    return value
}

var intValue : Int? {
    guard case let .integer(value) = self else { return nil }
    return value
}

并使用它

answer.id?.intValue