Thank you for your answer @Claude31 . I'm trying to get the vehicle make and model from the user. I have a .json file which has all car brand and models. I'm getting values from viewModel and this is my struct:
struct Car: Decodable, Identifiable {
enum CodingKeys: CodingKey {
case brand
case models
}
var id = UUID()
var brand: String
var models: [String]
}
In the first picker I want to select brand. Then I want to see models according to the brand I chose.
Picker("Brand", selection: $brandIndex) {
Text("Choose").tag(0)
ForEach(cars.indices, id: \.self) {
Text(cars[$0].brand).tag($0 + 1)
}
}
Picker("Model", selection: $modelIndex) {
Text("Choose").tag(0)
if brandIndex != 0 {
ForEach(cars[brandIndex - 1].models.indices, id: \.self) {
Text(cars[brandIndex - 1].models[$0])
.tag($0 + 1)
}
}
}
First, I select a brand and model, then when I change the brand, if the new brand does not have that value, I get the error I mentioned above. I thought that this situation would be solved if the modelIndex variable was set to 0 every time the brand was changed. Thank you so much.