0

I am populating a collectionView with items loaded from a remote web service:

if error == nil {
            do {
               
             self.chatsSorted = try JSONDecoder().decode([Chats].self, from: data!)
               print("mis compras ",data as Any)
                
                DispatchQueue.main.async {
                    completed()
                    print("Chats:", self.chatsSorted)
                }
                print(self.chatsSorted[0].id_chat)
                
            }catch{
                print("Error disp:",error)
            }
            

Some times the received JSON string contains null values for one or more keys values. When it is the case, the code launches an exception like this and the result is an empty collection View:

Error disp: valueNotFound(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 2", intValue: 2), CodingKeys(stringValue: "modelo", intValue: nil)], debugDescription: "Expected String value but found null instead.", underlyingError: nil))

I know that the error is due to null/nil keys values, but I would like to display the data also when there are keys values with null/nil values.

How can I solve this issue? Should I change the model class definition or should I try to avoid the exception on the code?

mvasco
  • 4,965
  • 7
  • 59
  • 120
  • 1
    Your model should either allow nil values (use optionals in your Codable model), or use a custom init to handle when it's nil, and set a default value. – Larme Sep 15 '20 at 17:10
  • @Larme, thank you for your comment. I prefer the second option. Would you mind to show me how to use a custom init in my case? – mvasco Sep 15 '20 at 17:15
  • 1
    https://stackoverflow.com/a/56146266/1801544 or other solutions – Larme Sep 15 '20 at 17:31

0 Answers0