I'm getting this error : Picker: the selection "3" is invalid and does not have an associated tag, this will give undefined results.
Because new brand doesn't have 3 values and .onChange
modifier is not working fast enough. Thanks for your help.
Picker("Marka", selection: $brandIndex) {
Text("Seçin").tag(0)
ForEach(cars.indices, id: \.self) {
Text(cars[$0].brand).tag($0 + 1)
}
}
.onChange(of: brandIndex) {
if modelIndex != 0 {
modelIndex = 0
}
}
Picker("Model", selection: $modelIndex) {
Text("Seçin").tag(0)
if brandIndex != 0 {
let _ = print(modelIndex) // I'm getting first 3 then 0. And I'm getting error.
ForEach(cars[brandIndex - 1].models.indices, id: \.self) {
Text(cars[brandIndex - 1].models[$0])
.tag($0 + 1)
}
}
}
@ FiratSirin You're right, you need an additional test:
if brandIndex != 0 && modelIndex <= cars[brandIndex - 1].models.count { // <<-- test modelIndex
Picker("Model", selection: $modelIndex) {
Text("Model Seçin").tag(0)
// if brandIndex != 0 {
let _ = print("modelIndex", modelIndex) // I'm getting first 3 then 0. And I'm getting error.
ForEach(cars[brandIndex - 1].models.indices, id: \.self) {
Text(cars[brandIndex - 1].models[$0])
.tag($0 + 1)
}
}
} else {
Text("Select a brand")
}
Here is the complete code I tested:
struct Car: Decodable, Identifiable {
enum CodingKeys: CodingKey {
case brand
case models
}
var id = UUID()
var brand: String
var models: [String]
}
struct ContentView: View {
@State var brandIndex = 0
@State var modelIndex = 0
var cars : [Car] = [
Car(brand: "VW", models: ["Golf", "Passat", "Up"]),
Car(brand: "Renault", models: ["Megane", "Twingo", "Zoe"]),
Car(brand: "Porsche", models: ["Carrera", "Taycan"])
]
var body: some View {
Picker("Marka", selection: $brandIndex) {
Text("Marka Seçin").tag(0)
ForEach(cars.indices, id: \.self) {
Text(cars[$0].brand).tag($0 + 1)
}
}
.onChange(of: brandIndex) {
print("changing brand", brandIndex)
if modelIndex != 0 {
modelIndex = 0
}
}
if brandIndex != 0 && modelIndex <= cars[brandIndex - 1].models.count {
Picker("Model", selection: $modelIndex) {
Text("Model Seçin").tag(0)
// if brandIndex != 0 {
let _ = print("modelIndex", modelIndex) // I'm getting first 3 then 0. And I'm getting error.
ForEach(cars[brandIndex - 1].models.indices, id: \.self) {
Text(cars[brandIndex - 1].models[$0])
.tag($0 + 1)
}
}
} else {
Text("Select a brand")
}
}
}