我正在学习swift
的课程。我想在数组中加载一些JSON格式的数据(使用swiftyJSON和alamoFire),然后在函数外部使用该数组。当我打印数组时,它是空的并在循环输出之前打印。如何填写naamArray2
内容naamArray
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController {
var naamArray = [String]()
var naamArray2 = [String]()
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Alamofire.request(.GET, "http://217.149.68.51:8080/xfind.php?userId=mike", parameters: ["foo": "bar"])
.responseJSON
{ response in
if let value = response.result.value
{
print("JSON: \(value)")
let json = JSON(value)
print(json["producten"][0]["productnaam"].stringValue)
let loopCounter = json["producten"].count
for i in 0...loopCounter
{
let tempstring = json["producten"][i]["productnaam"].stringValue
self.naamArray.append(tempstring)
}
print("\(self.naamArray)")
}
}
print("koekkoek")
print("tweede \(self.naamArray)")
naamArray2 = self.naamArray
}
答案 0 :(得分:0)
调用请求是以异步方式运行的,因此当您将其置于viewDidload
的底部时,它无法在有值时进行分配。
您可以创建函数调用assignValue并在请求成功后调用:
func assignValue() {
naamArray2 = self.naamArray
}
更改为:
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Alamofire.request(.GET, "http://217.149.68.51:8080/xfind.php?userId=mike", parameters: ["foo": "bar"])
.responseJSON
{ response in
if let value = response.result.value
{
print("JSON: \(value)")
let json = JSON(value)
print(json["producten"][0]["productnaam"].stringValue)
let loopCounter = json["producten"].count
for i in 0...loopCounter
{
let tempstring = json["producten"][i]["productnaam"].stringValue
self.naamArray.append(tempstring)
}
print("\(self.naamArray)")
assignValue()
}
}
}