Identifiable ID

I have a JSON from my backend which returns:

[
  {
    productId : 1
    name: productA
  },
  {
     productid: 2
     name: productB
  }
}

And on my SwiftUI project I have a model:

struct ProductModel: Identifiable, Codable, Hashable {
   //var id = UUID()
   var productId = Int
   var name = String
}

In my View, when I do a foreach to present all the products coming from my JSON, I got a message saying my model needs to be Identifiable to be using the foreach.

That was the reason I created the var id = UUID() on my model. Now I dont have the foreach error message, however, I get the error:

Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "id", intValue: nil)

Shouldn't it be ok since I am creating the ID on my model ?

Thank you !

Answered by ForumsContributor in

Both your JSON and code are not valid, you should better show the right things for readers not to be confused.

Have you tried to make it a computed property?

struct ProductModel: Identifiable, Codable, Hashable {
    var id: Int {productId}
    var productId: Int
    var name: String
}
Accepted Answer

You should be able to do something like ForEach(dataModel.products, id: \.productId) {product in .....

then you don't need Identifiable on your ProductModel struct, nor the var id: Int

Where an entity (struct or class) does not conform to Identifiable, you have to provide the id parameter and the referenced property must be unique for each occurrence, otherwise strange things happen!

The ForEach line above assumes that your products array is being supplied from a dataModel via @StateObject var dataModel = DataModel() etcetera

Regards, Michaela

Identifiable ID
 
 
Q