Swift Function解析JSON并返回字典数组 [英] Swift Function to parse JSON and return a array of dictionaries

查看:363
本文介绍了Swift Function解析JSON并返回字典数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个解析JSON的函数.函数的返回值是字典的array.不幸的是,我遇到的问题是赋值result = data as! [[String:AnyObject]]无法正常工作. print(data)返回了我的JSON,但是print(result)只给了我一个空数组.令人惊讶的是,方法print(result) 首先运行,然后运行方法print(data).

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.

我尝试过的代码:

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
}

推荐答案

Api调用以async(在后台)的方式工作,这就是为什么您需要使用swift closure而不是返回dictionary的原因.像这样更改代码

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

然后这样打电话

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

这篇关于Swift Function解析JSON并返回字典数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆