我是新的Swift中,我有添加元素到數組的問題不能添加元素到數組
我試圖從JSON存儲6個對象到數組。但陣列是零。
我看到它添加到陣列時,我調試它,我不知道爲什麼在完成請求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"
}
]
服務:
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
}
}
}
黃金類:
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.
}
}
這是因爲你錯過了異步概念。如果在'printGoldArray()'之前在'print(self.goldArray.count)'和'print(「print print」)''之前添加'print(「in alamofire closure」)'',你會看到打印不是你期望的。尋找「Swift + Closure + Async」。 – Larme
爲什麼你**強制unwrap **一個可選的('as!NSArray?')的可選項? – vadian