【问题标题】:How to iterate over a list of objects that do not have an id property如何遍历没有 id 属性的对象列表
【发布时间】:2020-09-10 19:29:05
【问题描述】:

这些是我从网络调用中填充的两个模型的示例。

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

}

我试图在列表中使用它们,但 CombinedValueModel 不符合 Identifiable。模型包含CombinedValueModels 的列表。

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

如何使迭代值成为可能?

我尝试将 id: \.self 提供给 List 但这使得 CombinedValueModel 必须符合 Hashable 并导致实现您自己的“==”函数。这导致 ValueModel 符合 EquatableHashable

有更简单的方法吗?

【问题讨论】:

    标签: arrays swift swiftui codable


    【解决方案1】:

    您可以使用从CodingKeys 中排除的id 属性来遵守Identifiable 协议。使用UUID 为您的结构的每个实例手动生成一个唯一标识符,如下所示:

    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
        }
    }
    

    【讨论】:

    • 完美运行
    • 旁注。如果您希望它在 id 上实际生成一个值,那么您必须将 UUID().uuidString 添加到结构中,而不仅仅是 UUID()
    猜你喜欢
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 2015-01-08
    • 2014-08-09
    相关资源
    最近更新 更多