Damiano Miazzi
Damiano Miazzi

Reputation: 2305

what is wrong on this SwiftUI List, not displaying the correct data

for study purpose I'm parsing some HTML data from a website. I collect this data and added to an array called "arrayDuty" inside my class DataManager: ObservableObject

var arrayDuty : [Duty] = []
    {
        didSet {
            objectWillChange.send() 
        }
    }

using the debug tool I can see the data inside my array (in this example 3 values):

array duty

On My ContentView i'm try to display a List with the data for each value of my array,

struct ContentView: View {
    @ObservedObject var dm : DataManager
    
    var body: some View {
        VStack {
            
            List(dm.arrayDuty){ item in
                Text(item.dutyDay)
            }
            
            Button(action: {
                dm.loadRoster()
            }, label: {
                Text("parse Table Roster")
            })
            
            Button {
                prt(array: dm.arrayDuty)
            } label: {
                Text("show")
            }

        }
    }
    func prt(array: [Duty]) {
        for item in array {
            print(item.dutyDay)
        }
    }
}

When I press on load roster button , the array is populated with the data correctly , the list update automatically but display the data wrong. I don't know why my list display always the same first value and not every value in the array.

array display

Upvotes: 2

Views: 314

Answers (1)

RTXGamer
RTXGamer

Reputation: 3714

Use @Published property in your Dm for arrayDuty and conform your Duty model to Hashable protocol:

@Published var arrayDuty = [Duty]()

Create a @StateObject for the Dm in the ContentView:

@StateObject var dm = Dm()

Content View Setup:

List(dm.arrayDuty, id: \.self) { item in
    Text(item.dutyDay)
}

Upvotes: 3

Related Questions