accessing specific value from JSON array swift 4

时间:2018-04-20 01:03:38

标签: arrays json swift xcode scope

Im trying build a quiz app which uses a open source api. Till now I have been able to parse the JSON and make the array global. The array prints as a whole, but whenever I try to specify a element I get the error "subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion".

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

My code

1 个答案:

答案 0 :(得分:0)

r?.question 字符串,而不是数组,因此您收到此错误。据我所知,您需要列表中的问题和答案。如果是这样,请检查以下代码:

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