I am trying to use multiple pickers with dynamic data in SwiftUI (XCode 11.3.1). The app sometimes crashes and sometimes freezes or shows the wrong data in the picker both in the simulator and on a real device running iOS 13.3.1. I tried the suggestions in the answers to this question with no success. What am I doing wrong?
import SwiftUI
struct DbItem : Identifiable {
var id: Int
var name: String
}
final class DbStore : ObservableObject {
let countries: [DbItem] = [DbItem(id: 0, name: "USA"), DbItem(id: 1, name: "France")]
let citymap:[Int:[DbItem]] = [0:[DbItem(id: 10, name: "New York"), DbItem(id: 11, name: "Los Angeles"), DbItem(id: 12, name: "Dallas"), DbItem(id: 13, name: "Chicago")], 1:[DbItem(id: 20, name: "Paris"), DbItem(id: 21, name: "Nice"), DbItem(id: 22, name: "Lille")]]
@Published var cities = [DbItem]()
@Published var country : Int = -1 {
willSet {
if newValue >= 0 {
self.id = UUID()
DispatchQueue.main.async { [newValue] in
self.cities = self.citymap[newValue]!
}
}
}
}
@Published var city : Int = -1 {
didSet {
}
}
}
struct ContentView: View {
@EnvironmentObject private var store: DbStore
var body: some View {
NavigationView {
Form {
VStack {
Picker(selection: $store.country,
label: Text("Country: ")
) {
ForEach(store.countries) { country in
Text(country.name)
}
}
Picker(selection: $store.city,
label: Text("City: ")
) {
ForEach(store.cities) { city in
Text(city.name)
}
}
.disabled(store.country < 0)
}
}
}
}
}