Swift Function to parse JSON and return a array of dictionaries

风流意气都作罢 提交于 2019-12-18 09:45:58

问题


I tried to write a function to parse a JSON. The return-value of the function is an array of dictionaries. Unfortunately, I have the problem that the assignment result = data as! [[String:AnyObject]] does not work. the print(data) returns my JSON wonderful back but the print(result) only gives me a empty array back. surprising it is that the method print(result) runs first and then the method print(data) run.

The code i have try:

import Foundation
import Alamofire
import SwiftyJSON

func getPlayers() -> Array<Dictionary<String, AnyObject>>  {

    var result = [[String:AnyObject]]()

    Alamofire.request(.GET, "http://example.com/api/v1/players", parameters: ["published": "false"])
        .responseJSON { (responseData) -> Void in
            if((responseData.result.value) != nil) {
                let response = JSON(responseData.result.value!)

                if let data = response["data"].arrayObject {
                    print(data)
                    result = data as! [[String:AnyObject]]
                }
            }
    }

    print(result)

    return result
}

回答1:


Api calling work in async (in background) manner that's why you need to use swift closure instead of returning dictionary. Change your code like this

func getPlayers(completion: (Array<Dictionary<String, AnyObject>>) -> ()))  {

    var result = [[String:AnyObject]]()

    Alamofire.request(.GET, "http://example.com/api/v1/players", parameters: ["published": "false"])
        .responseJSON { (responseData) -> Void in
            if((responseData.result.value) != nil) {
                let response = JSON(responseData.result.value!)
                if let data = response["data"].arrayObject {
                    print(data)
                    result = data as! [[String:AnyObject]]
                }
            }
            completion(result)
     }
}

And call like this

self.getPlayers() { (result) -> () in
     print(result)
}


来源:https://stackoverflow.com/questions/38683309/swift-function-to-parse-json-and-return-a-array-of-dictionaries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!