iosswiftswift4codable

Printing DecodingError details on decode failed in Swift


I'm starting to rewrite an application and I want to use Swift 4 Codable protocol to automatically convert json string to Objects and Structs.

Sometimes, specially at the beginning of coding, I encountered decoding problems, so I want to print these errors (whithout using always the debugger), in case some beans are not decoded correctly.

The problem is this:

enter image description here

As you can see, in the debugger, on "decodingError" object there is both:

My problem is that the only properties of that element, in the code, are errorDescription, failureReason, etc, that are ALL nil.

How can I print the values that are correctly displayed in the debugger?


Solution

  • DecodingError is an enum. In your case you have to catch the typeMismatch case and print the type and the context.

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