-1

Hi I have a struct like this

struct OrderCaches: Codable {
    var food, drink: [Food]?
}


struct Food: Codable{
    var id: Int?
    var name: String?
    var quantity: Double?
    var notes: String?
}

I want to get first index where id = productList[indexPath.row].id

I tried with:

let index = OrderCaches.firstIndex(where: {$0.food.id == productList[indexPath.row].id})

but not work I get this error "Value of type '[Food]?' has no member 'id'". How can I get the first Index? Thanks

TheCesco1988
  • 280
  • 1
  • 2
  • 10
  • The types here are really suspicious. What does it mean to have a `nil` quantity of a an unnamed `Food` with no ID or notes? Because that's currently possible given the types of the fields of `Food`, but it doesn't make any sense in real life – Alexander May 25 '20 at 22:01

1 Answers1

2

The function firstIndex is not a static member, but an instance member, hence you have to create an instance of OrderCache to get the index, like below:

let orderCaches = OrderCaches(food: [], drink: [])
let index = orderCaches.food?.firstIndex(where: { $0.id == productList[indexPath.row].id })
Frankenstein
  • 15,732
  • 4
  • 22
  • 47