swift - 在 Swift 4 中解码结构中的字符串或 int 值将返回字符串 ("1")

标签 swift decode decodable

我有一个结构,其中一些值会得到整数或字符串,所以我在我的结构中使用这个结构以正确的方式解析 JSON 但问题是当我想打印值时它会打印字符串(“1") 而不是 1。

 public struct  player1_result_sheet : Decodable {
    let ans_1 : QuantumValue?
    let ans_2 : QuantumValue?
    let ans_3 : QuantumValue?
    let ans_4 : QuantumValue?
}
 enum QuantumValue: Decodable {

    case int(Int), string(String)

    init(from decoder: Decoder) throws {
        if let int = try? decoder.singleValueContainer().decode(Int.self) {
            self = .int(int)
            return
        }
        if let string = try? decoder.singleValueContainer().decode(String.self) {
            self = .string(string)
            return
        }
        throw QuantumError.missingValue
    }
    enum QuantumError:Error {
        case missingValue
    }
}

这里是解码后的打印:

(self.res?.response?.detailData?[indexPath.row].player1_result_sheet?.ans_1!)!

最佳答案

如果你想在没有枚举包装器的情况下打印值,只需实现description:

extension QuantumValue: CustomStringConvertible {
    public var description: String {
        switch self {
        case let .string(string):
            return string
        case let .int(number):
            return "\(number)"
        }
    }
}

关于swift - 在 Swift 4 中解码结构中的字符串或 int 值将返回字符串 ("1"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53894747/

相关文章:

c++ - Xcode 10.3 构建失败 “Undefined symbols for architecture x86_64”

android - IllegalArgumentException Base64 到图像解码android

c++ - 将加密对象解密为 memcpy 的 char[]

gps - 解码SMS报告肯尼亚狮子的GPS位置

json - 解码具有相同信封但不同内容的 JSON 响应

swift - 如何使用 indexpathforselectedrow 从结构数组中获取实例?

ios - 通过子类和数十个 map 引脚将变量传递给新的 View Controller

Swift Realm 删除对象错误-写入事务

swift - 为具有失败响应的字典数组实现 Codable

json - 可解码的 JSONDecoder 处理相同值的不同编码键