I have a simple SwiftUI view with a Picker containing a list of objects from a data array. The Picker lists the objects just fine, but the selected value is not being saved to the binding variable $selectedCar. It returns empty string. This is the view in question:
struct GarageSpace: View { var currentUserID: String @Environment(\.presentationMode) var presentationMode @Binding var selectedPlaceID: String @Binding var selectedPlaceName: String @Binding var selectedPlaceDate: Date @Binding var selectedSpaceID: String @State var selectedCar: String @Binding var cars: CarArrayObject var body: some View { VStack{ Group{ Picker("Car", selection: $selectedCar) { if let cars = cars{ ForEach(cars.dataArray, id: \.self) {car in let year = car.year! as String let make = car.make as String let model = car.model! as String let string = year + " " + make + " " + model Text(string) //displays correctly in Picker } } } Spacer() if let cars = cars { Button { print("yes") print(selectedCar) //returns empty string } label: { Text("Confirm") } } } } } } The above view is displayed via a NavigationLink on the previous screen:
NavigationLink(destination: GarageSpace(currentUserID: currentUserID, selectedPlaceID: $selectedPlaceID, selectedPlaceName: $selectedPlaceName, selectedPlaceDate: $selectedPlaceDate, selectedSpaceID: $selectedSpaceID, selectedCar: "", cars: $cars)) { } This NavigationLink might be the culprit because I'm sending an empty string for selectedCar. However, it forces me to initialize a value with the NavigationLink.
Any ideas? Thanks!
EDIT: Added a tag of type String, still same outcome:
Text(string).tag(car.carID) EDIT: FOUND THE ISSUE! However, I'm still stumped. The selection variable is empty because I wasn't pressing on the Picker since I only had one item in the array. How can I get the Picker to "select" an item if it's the only one in the array by default?
Text(string).tag(car.id)and still get an empty string. Thanks thoughcar.ida String? The tag need to match theselectedCar: Stringin type.p car.carID (String) $R0 = "N2cl4SD47PBWGjDrei2p"is what I get when I put a breakpoint within the ForEach loop for the Picker.onAppear { if let cars = cars { selectedCar = (cars.dataArray.first != nil) ? cars.dataArray.first!.carID : "" } }