如何从 VStack 列表中的项目创建 Json?

How to create Json from items in List in VStack?

我有以下结构

struct ContentView: View {

    @State private var usedWord = [String]()
    @State private var  rootWord = ""
    @State private var newWord = ""

    var manager = HttpRequest()

    var body: some View {
        NavigationView{
            VStack{
                TextField("Enter your symptom", text: $newWord, onCommit: addNewWord)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .autocapitalization(.none )
                    .padding()
                List {
                    ForEach(usedWord, id: \.self){
                    Text([=11=])
                    }
                    .onDelete(perform: deleteItem)
                }

                Button("Get diagnose"){
                    // here we plac logic of sending request to API server

                }
            }
        .navigationBarTitle(rootWord)
        }
    }

    func addNewWord() {
        let answer = newWord.lowercased( ).trimmingCharacters(in: .whitespacesAndNewlines)
        guard answer.count > 0 else {
            return
        }

        // extra validation to come
        usedWord.insert(answer, at: 0)
        newWord = ""
    }

     func deleteItem(at indexSet: IndexSet) {
        self.usedWord.remove(atOffsets: indexSet)
    }
}

这是其中的文本项列表。在 Button("Get diagnose") 中,我想遍历 List 并创建 Json 对象以将其发送到 API 服务器。 Json 结构类似于 {'1': 'pain in chest', '2': 'headache'}。我有一个请求函数,但我不知道如何创建 Json

您不需要遍历 list。您应该遍历列表的数据,例如:

Button("Get diagnose"){
    // here we plac logic of sending request to API server
    for word in self.usedWord.enumerated() {
       print(word.offset, ":", word.element)
    }
}

我不知道您如何需要 JSON 但是,您可以从中构建一个 dictionary

let dictionary = Dictionary(uniqueKeysWithValues: zip(self.usedWord.indices, self.usedWord))

JSONData 喜欢:

let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: [])