0

我需要ForEach一个结构数组,因此它们每个都必须符合Identifiable协议。但由于这些结构是从获取的 JSON 中解码的,它们已经有一个 id 属性——在我的数据库中使用的 id。我应该给他们另一个 UUID 来满足Identifiable协议吗?如果没有,我如何使用现有属性作为 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()
}
4

1 回答 1

3

使用计算属性返回现有属性作为 ID:

struct Event: Codable, Identifiable {
    let eventID: String
    //...other properties
    
    var id: String { eventID } //or whatever
}
于 2021-11-09T22:54:39.873 回答