【发布时间】:2018-09-30 14:56:23
【问题描述】:
我正在尝试构建一个使用开源 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])
}
}
【问题讨论】:
标签: arrays json swift xcode scope