Learn Courses My Dashboard

Error: Value of type [items] has no member last_updated

In my ViewModel, I stated as - @Published var myDataArray = Model. However, in my struct Model, I have items as property which I’m not able to access via List or ForEach in the Content Model. Please let me know where am I going wrong.

Blockquote

import SwiftUI

struct ContentView: View {

@ObservedObject var model = ContentModel()

var body: some View {
    
    ForEach(model.myDataArray, id: \.self) { item in
        
        Text(item.purchase_order_number)    // This works just fine

        Text(item.items.last_updated)  // Not able to access this property. Please suggest.
        
    }
}

}


import Foundation

struct Model: Decodable, Hashable {

var purchase_order_number: String

var items: [Items]

}

struct Items: Identifiable, Decodable, Hashable {

var id: Int

var product_item_id: Int

var quantity: Int

var last_updated_user_entity_id: Int

var transient_identifier: String

var active_flag: Bool

var last_updated: String

}

Blockquote

You are trying to access item.items.last_updated but items is declared as an array. You need to indicate which item in the items array you are trying to access, either by index (e.g., by looping through items) or using something like .first.

A couple points of style:

  1. You should rename your Items struct to Item since it indicates one single item. Then the items property in your Model would be declared as var items: [Item] because it is an array of Item objects.
  2. Swift convention is not to use snake case for naming variables but to use camel case instead. So purchaseOrderNumber instead of purchase_order_number.

And an FYI: When you post code on the forums, please place three backticks ``` on the line before your code and three backticks ``` on the line after in order to format the code block for proper display. You can also highlight an entire code block and click the </> button on the toolbar to wrap the block for you.

This makes it far easier to read and also makes it easier for other posters to copy/paste the code in order to test solutions and such.

Doing this will ensure that you end up with something like this:

import Foundation

struct Model: Decodable, Hashable {
    var purchase_order_number: String
    var items: [Items]
}

instead of this:

import Foundation

struct Model: Decodable, Hashable {

var purchase_order_number: String

var items: [Items]

}