无法让 ForEach 循环在 SwiftUI 中使用嵌套的 JSON 数据

Can't get ForEach loop to function with nested JSON data in SwiftUI

我正在尝试使用 ForEach 我的服务模型数据中的联系人创建列表。

型号如下;

struct ServiceContract: Codable, Identifiable {
    let id: String
    let name: String
    let latitude: Double
    let longitude: Double
    let maplogo: String
    let customerName: String
    let postcode: String
    let serviceCompany: String
    let projectNumber: Int
    let renewalDate: String
    let contractTerm: Int
    let annualValue: Double
    let paymentTerms: String
    let relationship: String
    let geuOEM: String
    let additionalSpendToDate: Double
    let type: String
    let contacts: Contacts
    let service: [String]
    let notes: String
    
    // Computer Property
    var location: CLLocationCoordinate2D {
        CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }
}

struct Contacts: Codable {
    let contact: [Contact]
}

struct Contact: Codable {
    let contactFirstName: String
    let contactLastName: String
    let contactNumber: String
    let contactEmailAddress: String
}

所以基本上每个服务合同(确实符合 Identifiable)可以有多个联系人。这是通过使用几个额外的结构来实现的。

所以问题来了。我只想为特定服务合同创建每个联系人的列表,但我无法使 ForEach 起作用,因为使用 \.id 不起作用,而且我无法使用 serviceContract.contacts.contact 因为这不符合 Identifiable.

以下代码摘录:

VStack {
    ForEach(serviceContract.contacts.contact) { cont in
        Text("\(cont.contactFirstName)")
    } //: LOOP
}

serviceContract.contacts 中的每个联系人都必须是唯一的。如果 contactNumber 是唯一的,那么你可以这样做

ForEach(serviceContract.contacts.contact, id: \.self.contactNumber)

如果Contact中的none个字段是唯一的,那么你可以使整个Contact符合Hashable(这将需要一些额外的代码),然后使用整个 Contact 实例作为标识符:

ForEach(serviceContract.contacts.contact, id: \.self)