[英]accessing specific value from JSON array swift 4
我正在尝试构建一个使用开源API的测验应用程序。 到目前为止,我已经能够解析JSON并使数组成为全局数组。 数组将整体打印,但是每当我尝试指定一个元素时,都会出现错误“下标不可用:无法对带Int的字符串进行下标,请参阅文档注释以进行讨论”。
import UIKit
import Alamofire
import PKHUD
import SwiftyJSON
struct Result : Decodable{
let question : String
let correct_answer : Bool
}
var r: Result?
class ViewController: UIViewController {
var r: Result?
var myResults = [Result]()
override func viewDidLoad() {
getQuestionNew()
super.viewDidLoad()
// self.r = Result()
printTest()
}
func getQuestionNew(){
// this is the main screwed up function
let parameters: Parameters = ["amount": 15, "type":"boolean"]
Alamofire.request("https://opentdb.com/api.php", method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
// print("Request: \(String(describing: response.request))") // original url request
// print("Response: \(String(describing: response.response))") // http url response
// print("Result: \(response.result)")
if((response.result.value) != nil) {
let swiftyJsonVar = JSON(response.result.value!)
//print(swiftyJsonVar["results"])
let results = swiftyJsonVar["results"].arrayValue
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()
// print(self.r)
})
// label.text = allQuestions.list[questionNumber].questionText
}
}
}
func printTest(){
//error prone
print(r?.question[2])
}
}
您的r?.question是String ,而不是array ,所以您遇到了此错误。 据我了解,您需要列表中的“问题与答案”。 如果是这样,请检查以下代码:
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?
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.