How to iterate over a list of objects that do not have an id property

Viewed 363

These are examples of two models that I have that are populated from network calls.

struct CombinedValueModel : Codable{

    let identifiers: [ValueModel]

    let descriptors: [ValueModel]

    let amount: Double
}

struct ValueModel : Codable, Identifiable{

    let id: String

    let name: String?

    let value: String

}

I am trying to use them in a list but the CombinedValueModel does not conform to Identifiable. Model contains a list of CombinedValueModels.

List(Model.values){ value in
    Text("$\(value.amount, specifier: "%.2f")")
}

How do I make it possible to iterate over the values?

I have tried giving the id: \.self to the List but that makes it so that the CombinedValueModel has to conform to Hashable and that leads to implementing your own "==" func. That leads to making ValueModel conform to Equatable and Hashable.

Is there an easier way to do this?

1 Answers

You can conform to Identifiable protocol using an id property, that you exclude from your CodingKeys. Manually generate a unique identifier for each instance of your struct using UUID, like this:

struct CombinedValueModel: Codable, Identifiable {
    let identifiers: [ValueModel]
    let descriptors: [ValueModel]
    let amount: Double
    let id = UUID().uuidString

    // Need to add CodingKeys enum to exclude id from being decoded
    enum CodingKeys: CodingKey {
        case identifiers
        case descriptors
        case amount
    }
}
Related