Search code examples
swiftpicker

SwiftUI Picker does not 'pick data' when using struct data for source


I cannot find an answer which I am sure will be simple!. the Picker displays all the values without problem but it does not pick the selected value. I try by adding ', id: .self.id' in ForEach(section.serie, id: .self.id) but this does not change anything.

Structures used as 'tables' for all data

struct Eseries: Codable, Identifiable {
   var id: UUID
   var name: String
   var serie: [EserieData]
}

struct EserieData: Codable, Equatable, Identifiable {
   var id: UUID
   var name: String
   var values: [String]

Extract of the json file

[
   {
      "id": "EF1CC5BB-4785-4D8E-AB98-5FA4E00B6A66",
      "name": "e-series",
      "serie": [
         {
            "id": "EDCD038C-036F-4C40-826F-61C88CD84DDD",
            "name": "E3 50%",
            "values": ["100", "220", "470"]
         },

Extract of ContentView

//load data from json file
   let eserie = Bundle.main.decode([Eseries].self, from: "eseries.json")

   @State private var selectedSerie = "E24 5%"
    
   VStack {
      Text("E-Serie")
      Picker("E-Serie", selection: $selectedSerie) {
         ForEach(eserie) { section in
            Section() {
               ForEach(section.serie) { item in
                  Text(item.name)
               }
            }
         }
      }
      .padding()
      .frame(maxWidth: geometry.size.width / 3)
      .clipped()
      .border(Color.red)
   }

Picker with its data


Solution

  • I do not know the answer. I do not use json anymore or it would be too complicated just to extract the 'data' for init the table. I created 2 tables. One for each Picker and this work fine.