问题
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