Search code examples
swiftswiftuipicker

Assign api json results to SwiftUI Picker


I have these struct:

 struct Problems: Codable {
    var id: Int
    var type: String
}

and this state:

@State private var issues = [Problems]()

I fetch the results from api like this:

let decoded = try JSONDecoder().decode([Problems].self, from: data)
                            self.issues = decoded
                            print(decoded)

and it prints:

Premier_Service.AddTaskView.Problems(id: 2, type: "Door"), 
Premier_Service.AddTaskView.Problems(id: 3, type: "Water"),
 Premier_Service.AddTaskView.Problems(id: 4, type: "Elevator"),

I want to assign the issues to picker, but I don't know how after trying many other codes


Solution

  • Here is a working example ... I created some dummy data.

    Create another State variable, which holds your selected value and then pass all your other Problems object to the Picker.

    struct Problems: Codable, Hashable {
        var id: Int
        var type: String
    }
    
    struct ContentView: View {
        @State private var issues = [Problems(id: 0, type: "Big Problem"), Problems(id: 1, type: "World Problem")]
        @State var selectedIssue: Problems? = nil
        var body: some View {
            Picker("Choose", selection: $selectedIssue, content: {
                ForEach(issues, id:\.self) { problem in
                    Text(problem.type).tag(problem as Problems?)
                }
            })
            .onAppear(perform: {
                selectedIssue = issues.first
            })
        }
    }