I'm new in Swift and I have issue with adding an element to an Array
I'm trying to store 6 objects from JSON to Array. But the Array is nil.
I see it add to Array when I debug it, I have no idea why it's nil after finished request JSON?
JSON:
[
{
"amount": "20.0",
"date": "10/07/2016"
},
{
"amount": "21.0",
"date": "11/07/2016"
},
{
"amount": "16.0",
"date": "12/07/2016"
},
{
"amount": "30.0",
"date": "13/07/2016"
},
{
"amount": "50.0",
"date": "14/07/2016"
},
{
"amount": "33.0",
"date": "15/07/2016"
}
]
Service:
class DownloadService {
static let instance = DownloadService()
//static var goldArray = [Gold]()
var goldArray = [Gold]()
func getData() {
Alamofire.request("https://rth-recruitment.herokuapp.com/api/prices/chart_data", headers: headers).responseJSON { response in
if let objJson = response.result.value as! NSArray?{
for element in objJson {
let data = element as! NSDictionary
let amount = data["amount"] as! String
let date = data["date"] as! String
let gold = Gold(amount: amount, date: date)
self.goldArray.append(gold)
print(self.goldArray.count)//print 1 to 6
}
}
}
printGoldArray()
}
func printGoldArray(){
for element in self.goldArray {
print(element)//print nothing
}
}
}
Gold class:
class Gold{
let amount:String
let date: String
init(amount: String, date: String) {
self.amount = amount
self.date = date
}
}
ViewController:
class ViewController: UIViewController {
//var dataArray = [Gold]()
override func viewDidLoad() {
super.viewDidLoad()
DownloadService.instance.getData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
print("in alamofire closure")beforeprint(self.goldArray.count)andprint("calling print")just beforeprintGoldArray(), you'll see that the order of the print is no the one you expect. Look for "Swift + Closure + Async".as! NSArray?) ??