Search code examples
swiftuiprotocolsidentifiable

Swift Conform to Identifiable with existing property


I need to ForEach an array of structs, and so they each must conform to the Identifiable protocol. But since these structs are decoded from fetched JSON's, they already have an id property--the id used in my database. Should I give them another UUID to satisfy the Identifiable protocol? If not, how do I use an existing property as an id?

struct Event: Codable, Identifiable {
    let eventID: String
    let description: String
    let date: String
    let location: String
    let hostID: String
    let hostName: String

    // need?
    let id = UUID()
}

Solution

  • Use a computed property to return an existing property as the ID:

    struct Event: Codable, Identifiable {
        let eventID: String
        //...other properties
        
        var id: String { eventID } //or whatever
    }