首页 > 解决方案 > 通过解码器查看还有哪些数据需要解码

问题描述

我正在使用 Codable 的 Swiftt 4 项目中工作。但是,我收到以下错误:

No value associated with key CodingKeys(stringValue: "postable_type", intValue: nil) ("postable_type").

现在我想知道如何最好地调试它。是否有可能查看 Codable 试图在我的模型中塞入哪些数据?特别是因为在这种情况下使用了相当高级的嵌套,我认为它在这里会是一个真正的救星......

谢谢 :)

标签: swiftcodable

解决方案


Codable错误非常具有描述性。对于调试,请使用此catch块获取详细的错误消息:

} catch DecodingError.dataCorrupted(let context) {
    print(context)
} catch DecodingError.keyNotFound(let key, let context) {
    print("Key '\(key)' not found:", context.debugDescription)
    print("codingPath:", context.codingPath)
} catch DecodingError.valueNotFound(let value, let context) {
    print("Value '\(value)' not found:", context.debugDescription)
    print("codingPath:", context.codingPath)
} catch DecodingError.typeMismatch(let type, let context)  {
    print("Type '\(type)' mismatch:", context.debugDescription)
    print("codingPath:", context.codingPath)
} catch {
    print("error: ", error)
}

两者都debugDescription告诉codingPath你到底哪里出了问题。


推荐阅读