异步填充数组,但返回空数

时间:2017-09-01 14:13:48

标签: ios arrays swift tvos

我正在尝试创建一个使用在线休息API的应用程序。它通过URLSession检索数据。在do{}方法中,正确填充整个数组。但是,当我返回数组时,突然之间它完全是空的。有人可以向我解释我做错了吗?

// Makes a request to the API
func makeRequest(url: URL) -> Array<Any>{
    var allItems = [[ApiItem]]()

    // Make request
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let data = data else { return }

        // Do the request
        do{
            // Get the JSON
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: AnyObject]

            // Get the right entry
            let results = json["items"] as? [AnyObject]

            // Loop through the results
            for r in results! {
                // Create a item
                let item = ApiItem(json: r as! [String : Any])

                // Add them to the array
                allItems.append([item])

                print("Items in array after appending: \(allItems.count)") // The entire array gets correctly filled here
            }

        } catch let jsonErr{
            print("JSON ERROR! \(jsonErr)")
        }
    }.resume()

    return allItems // The array is empty right here
}

0 个答案:

没有答案