Search code examples
dictionaryswiftuiforeachiteration

Iterating a api dictionary in ForEach


How to Iterate a API dictionary in ForEach. I have a dictionary and it consists of another dictionary in it. How to display those dictionary values in contentView?

My api structs:

struct userDataModel: Codable {
    let status: Bool?
    let message: String?
    let data: DataClass
}
struct DataClass: Codable {
    let id, phoneNumber, email, countrycode: String?
    let loginType: String?
    let otp: Int?
    let bookingInfo, cancellationInfo: [Any?]
    let token: String?
    let isHost: Bool?
    let wishList: [String]
    let contacts, review: [Any?]
    let createdAt, updatedAt: String?
    let v: Int?
    let dob, firstName, lastName: String?
    let isOnline: Bool?
    let lastSeen: String?
    let isExperience: Bool?
}

ContentView code:

struct UserData: View {
    
    @StateObject var api = userData()
    
    var body: some View {
        
        ForEach(api.responses!, id:\.self) { todo in
            Text(todo.firstName!)
        }
        .onAppear {
            api.loadData()
        }
    }
}

Network Class Published variables:

@Published var records: userDataModel? @Published var responses: DataClass?


Solution

  • As the answer provided by @workingdog support Ukraine, No need of ForEach here. Tried as Text(api.responses?.firstName ?? "no name") and in network class @Published var records: UserDataModel? is enough to bring the details out.