【发布时间】:2016-01-09 00:37:26
【问题描述】:
我面临的问题是我无法使用 JSON 数据填充空数组,并且在 StackOverflow 上找不到类似的问题。
在函数本身中,我可以获得空数组并在函数中填充数组。然后在 downloadRestaurantDetails 函数中调用 print 函数来查看我解析的信息。
但我无法填充函数外部的原始空数组,以便我可以获取填充的数组并在不同的函数中使用它。
import UIKit
import GoogleMaps
import Alamofire
import SwiftyJSON
class ViewController: UIViewController {
var placeIDArray = [String]()
var placeID: String!
override func viewDidLoad() {
super.viewDidLoad()
downloadRestaurantDetails { () -> () in
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func downloadRestaurantDetails(completed: DownloadComplete) {
//url is acquired through a file created for global variables
Alamofire.request(.GET,url).responseJSON { (response) -> Void in
if let value = response.result.value {
let json = JSON(value)
//Acquire All place_id of restaurants
if let results = json["results"].array {
for result in results {
if let allPlace_ID = result["place_id"].string {
//Add All place_id's into an array
self.placeIDArray.append(allPlace_ID)
}
}
}
}
// i call this method to check and see if there is anything placed in the array outside of the downloadRestaurantDetails method.
func check() {
if self.placeIDArray.count > 1 {
print(self.placeIDArray)
} else {
print(self.placeIDArray.count)
}
}
总结一下,我想解决的问题,
- 我想解析 place_id 并将生成的字符串放在 地点 ID 数组。我能够解析数据并将值存储在函数内的 placeIDArray 内。我无法将解析后的数据存储在函数之外的空数组中。我曾认为通过使用 self.placeIDArray 将解析的数据分配给数组。但似乎并非如此。
【问题讨论】:
-
仍然对此感到困惑,有人有想法吗?
-
当您检查数据是否已分配给
placeIDArray时,您在哪里尝试访问它? -
我创建了一个函数来检查我是否可以访问数组中的数据并将其打印到调试屏幕,它给我的计数为 0 但是当我在函数中打印它之后self.placeIDArray.append(allPlace_ID) 然后所有元素都按照我想要的方式正确打印。所以这让我建议不要在函数之外分配元素。如果这是正确的逻辑?
-
元素应该被分配到函数之外。你在回调中调用
check()吗?例如。downloadRestaurantDetails { () -> () in self.check()}? -
我在回调外部调用 check,但在 viewDidLoad 内部调用。
标签: arrays json swift google-places-api google-maps-sdk-ios