內部數組我有一個UIPickerView
我想填充值的數組。值的數組來自我的一個類中的函數(使用json獲取值然後將它們放入數組中)。數據正在成功抓取,並添加到函數內的數組中,但由於某種原因它不會返回。需要從一個函數返回我
這裏是我的類:
class Supplier {
var supplierId: Int
var supplierName: String
init(id: Int, name: String){
supplierId = id
supplierName = name
}
static func arrayOfSupplierNames() -> [String] {
let urlString = Constants.Urls.Suppliers.List;
let session = NSURLSession.sharedSession();
let url = NSURL(string: urlString)!;
var suppliers: Array<String> = []
session.dataTaskWithURL(url) { (data: NSData?, response:NSURLResponse?, error: NSError?) -> Void in
if let responseData = data {
do {
let json = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments) as! Dictionary<String, AnyObject>;
if let suppliersDictionary = json["suppliers"] as? [Dictionary<String, AnyObject>] {
for aSupplier in suppliersDictionary {
if let id = aSupplier["id"] as? Int, let name = aSupplier["supplierName"] as? String {
let supplier = Supplier(id: id, name: name)
suppliers.append(supplier.supplierName)
}
}
}
}catch {
print("Could not serialize");
}
}
}.resume()
return suppliers
}
}
這似乎是工作,因爲當我調試,我可以看到被添加到陣列中的值。我在我的ViewController另一個函數運行該功能,並將其添加到本地陣列,但是從函數返回數組似乎並沒有被添加到視圖控制器的陣列:
func populateSuppliersArray() {
let sup:Array = Supplier.arrayOfSupplierNames()
for s in sup {
supplierArray.append(s) //supplierArray is at the top scope of view controller.
}
}
我還送類函數是靜態的,所以我不必爲了使用函數而初始化類。我不確定這是否正確。當我在調試時查看sup
變量時,它具有零值。
你的函數返回一個空數組。 –