将 api json 个结果分配给 SwiftUI Picker

Assign api json results to SwiftUI Picker

我有这些结构:

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

这个状态:

@State private var issues = [Problems]()

我像这样从 api 获取结果:

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

并打印:

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

我想将问题分配给选择器,但在尝试了很多其他代码后我不知道如何做

这是一个工作示例...我创建了一些虚拟数据。

创建另一个 State 变量,它保存您选择的值,然后将所有其他 Problems 对象传递给选择器。

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
        })
    }
}