Search code examples
swiftswiftuiswiftui-listdecodableidentifiable

How to make my struct Identifiable? It has a unique numeric uid field


In a simple project at Github I am trying to download a list of JSON objects:

struct TopResponse: Codable {
    let data: [Top]
}

struct Top: Codable /*, Identifiable */ {
    let uid: Int
    let elo: Int
    let given: String
    let photo: String?
    let motto: String?
    let avg_score: Double?
    let avg_time: String?
}

This works well and as the next step I would like to display it in a SwiftUI List and thus add Identifiable to the struct.

Unfortunately, this produces the compile error Type 'Top' does not conform to protocol 'Identifiable':

error 1

By design of my backend app the field uid is a unique number.

So I am trying to fix the compile error by changing its type from Int to ObjectIdentifier, but the Swift compiler is still not happy with the new error Type 'Top' does not conform to protocol 'Decodable'

error 2

What is happening here, is the compiler now maybe missing the uid field for decoding JSON? (and how could it possibly know that the incoming server data has such a field?)


Solution

  • Identifiable requires that your struct have an id property, it doesn't find the best suited one automatically.

    If you want to use uid as the id property, implement it like this:

    var id: Int { uid }