Arrays 从JSON数组swift 4访问特定值
我正在尝试构建一个使用开源api的测验应用程序。到目前为止,我已经能够解析JSON并使数组全局化。数组作为一个整体打印,但每当我尝试指定一个元素时,就会出现错误“subscript”不可用:无法将字符串下标为Int,请参阅文档注释以进行讨论”Arrays 从JSON数组swift 4访问特定值,arrays,json,swift,xcode,scope,Arrays,Json,Swift,Xcode,Scope,我正在尝试构建一个使用开源api的测验应用程序。到目前为止,我已经能够解析JSON并使数组全局化。数组作为一个整体打印,但每当我尝试指定一个元素时,就会出现错误“subscript”不可用:无法将字符串下标为Int,请参阅文档注释以进行讨论” 您的r?。问题是字符串,而不是数组,因此出现了此错误。据我所知,您需要列表中的问题和答案。如果是,请检查以下代码: func printTest(){ for element in myResults { print
您的r?。问题是字符串,而不是数组,因此出现了此错误。据我所知,您需要列表中的问题和答案。如果是,请检查以下代码:
func printTest(){
for element in myResults {
print("Q:", element.question)
print("A", element.correct_answer)
}
}
在for循环外部调用printTest():
results.forEach({ (item) in
//print("Printing Item \(item["question"].stringValue)")
// print("Printing Item ?\(item)")
self.r = Result(question: item["question"].stringValue, correct_answer: item["correct_answer"].stringValue == "True" ? true : false)
self.myResults.append(self.r!)
// self.printTest()
})
// call here after loop
self.printTest()
[编辑1]您的完整结构应如下所示:
struct Result : Decodable {
let incorrect_answers : [Bool]?
let correct_answer : Bool?
let type : String?
let category : String?
let difficulty : String?
let question : String?
}
我实现了您的方法,并将“question”和“correct_aswer”更改为数组,但现在这两个属性的所有值都存储在同一数组元素下。例如,问题的所有值都在“element.question[0]”下,“element.question[1]”将导致致命错误。指向问题的链接是“我无法访问该链接。抱歉,请尝试此新链接…”您无法更改可解码结构,它应该与服务器响应类似。我实际上不知道数据将如何处理,API链接是“”。你能提供示例代码吗?
struct Result : Decodable {
let incorrect_answers : [Bool]?
let correct_answer : Bool?
let type : String?
let category : String?
let difficulty : String?
let question : String?
}