ForEach through Indices SwiftUI

96 views Asked by At

I'm attempting to use Contentful CMS and iterate through the array of data so I can display it in groups of Title, Style & Description in horizontal tiles. I was able to do it with hard coded array of data but I am unable to do it with this...

I've included my View, View Model & Model, as you'll see the model holds my API call, my View Model handles just my identifiable data, then my View handles my view itself.

// MARK: - View

struct BeerListView: View {
    @ObservedObject var draftVM = BeerModel()
    
    var body: some View {
        
        
        VStack {
            ForEach(draftVM.draftBeerArray.indices, id: \.self) { item in
                VStack {
                    Text(item.title)
                    Text(item.style)
                    Text(item.description)
                }
            }
        }
    }
}

// MARK: - View Model

struct BeersData: Identifiable {
    var id = UUID()
    var title: String = ""
    var style: String = ""
    var description: String = ""
}

// MARK: - Model

private let client = Client(spaceId: "SPACEID", accessToken: "SUPERSECRETTOKEN")

func getArray(id: String, completion: @escaping ([Entry]) -> ())  {
    let query = Query.where(contentTypeId: id)
    
    client.fetchArray(of: Entry.self, matching: query) { result in
        switch result {
        case .success( let array):
            DispatchQueue.main.async {
              completion(array.items)
                print(result)
            }
        case.failure(let error):
            print(error)
        }
    }
}


class BeerModel: ObservableObject  {
    @Published var draftBeerArray: [BeersData] = beerArray
        
    init() {
        getArray(id: "beers") { (items) in
            items.forEach { (items) in
                self.draftBeerArray.append(BeersData (
                    title: items.fields["title"] as! String,
                    style: items.fields["style"] as! String,
                    description: items.fields["description"] as! String))
            }
        }
    }
}
1

There are 1 answers

0
Asperi On

If you iterate by indices then your closure argument is index, so you have to access array by index, like

ForEach(draftVM.draftBeerArray.indices, id: \.self) { index in
    VStack {
        Text(draftVM.draftBeerArray[index].title)

If you want access item, then you have to iterate by items (they are identifiable already)

ForEach(draftVM.draftBeerArray, id: \.self) { item in
    VStack {
        Text(item.title)