Home > front end >  Can't get ForEach loop to function with nested JSON data in SwiftUI
Can't get ForEach loop to function with nested JSON data in SwiftUI

Time:12-20

I am literally pulling my hair out (and I don't her much to start with) on trying to create a list using a ForEach on contacts within my service model data.

The model is as below;

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
}

So basically each service contract (that does conform to Identifiable) can have multiple contacts. This is achieved by utilising a couple of extra structs.

So to the problem. I want to simply create a list of each contact for a particular service contract, but I cannot get the ForEach to function, as using the .id doesn't work, and I can't use the serviceContract.contacts.contact as this does not conform to Identifiable.

Any ideas?

Extract of code below;

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

CodePudding user response:

Each contact in serviceContract.contacts must be unique. If contactNumber is unique then you can do this

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

If none of the fields in Contact are unique, then you can make the whole Contact conform to Hashable (this will require some additional code), and then use the whole Contact instance as the identifier:

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