在Swift中打印有关解码的DecodingError详细信息失败

smu*_*uka 4 ios swift swift4 codable

我开始重写应用程序,我想使用Swift 4 Codable协议自动将json字符串转换为Objects and Structs。

有时,特别是在编码开始时,我遇到了解码问题,因此我想打印这些错误(不使用调试器),以防某些Bean无法正确解码。

问题是这样的:

在此处输入图片说明

如您所见,在调试器中,“ decodingError”对象上同时存在两种:

  • 出现问题的密钥(NominativoModel.denNome)
  • 遇到的错误(预期对数组bla bla bla进行编码...)。

我的问题是,代码中该元素的唯一属性是errorDescription,failureReason等,均为nil。

如何打印在调试器中正确显示的值?

Tar*_*ras 11

catch let error as DecodingError {
   switch error {
            case .typeMismatch(let key, let value):
              print("error \(key), value \(value) and ERROR: \(error.localizedDescription)")
            case .valueNotFound(let key, let value):
              print("error \(key), value \(value) and ERROR: \(error.localizedDescription)")
            case .keyNotFound(let key, let value):
              print("error \(key), value \(value) and ERROR: \(error.localizedDescription)")
            case .dataCorrupted(let key):
              print("error \(key), and ERROR: \(error.localizedDescription)")
            default:
              print("ERROR: \(error.localizedDescription)")
            }
   }
Run Code Online (Sandbox Code Playgroud)


vad*_*ian 8

DecodingError是一个枚举。你的情况,你必须catchtypeMismatch情况下,打印typecontext

catch let DecodingError.typeMismatch(type, context)  {
   print("Type '\(type)' mismatch:", context.debugDescription)
   print("codingPath:", context.codingPath)
}
Run Code Online (Sandbox Code Playgroud)