我刚开始在Swift 4中编码,需要帮助解析测验应用程序的JSON。我设法解析了JSON,但是包含数组的变量"r“被本地化在函数中。我试图使它成为一个全局变量,但没有成功。我使用的是swiftyJSON和Alamofire,但如果正确解释了新方法,请不要介意切换方法。如果可能的话,Example/functional代码会更好。谢谢
//struct declaration
struct Result : Decodable{
let question : String?
let correct_answer : Bool?
}
//var declaration inside class
var myResults = [Result]()
//networking and parsing
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)")
var r = Result(question: item["question"].stringValue, correct_answer: item["correct_answer"].stringValue == "True" ? true : false)
print(r)
self.myResults.append(r)
// print(r)
})
}
}
}发布于 2018-04-19 11:44:40
将此代码用于变量r声明
var r: Result?在ViewDidLoad()中初始化这个变量r
self.r = Result()https://stackoverflow.com/questions/49912032
复制相似问题