我正在尝试将来自 API 调用的数据附加到我的对象中。我的 for 循环附加了它,但我只能在 API 调用中读取它。为什么?看不懂。
我有自定义数组对象:
var locations: [Locations] = []
这是我的 API 调用:
Configuration().API_URL.get("test") { (error, data: [Response]?) in
for response in data!{
self.locations.append(Locations(latitude: response.latitude))
}
//If I print the print(locations) here, it prints
}
//If I do the print(locations) here(outside of API call), it does print empty object
如果我附加它并且值确实存在,为什么我无法从 API 调用之外的位置获取输出?我敢肯定这是个愚蠢的问题,但我的想法已经被打破了。
最佳答案
您正在使用异步调用的闭包。
这是一个有点宽泛的话题,但本质上是调用 get
后花括号中的所有内容,即这些内容:
{ (error, data: [Response]?) in
for response in data! {
self.locations.append(Locations(latitude: response.latitude))
}
//If I print the print(locations) here, it prints
}
是在网络调用完成后执行的代码。您正在将一个“闭包”或稍后要执行的代码块传递给 get()
方法。
因为它没有立即被调用,所以在调用 get()
之后,您的代码将继续到下一行,正如您所注意到的,locations
是空的。
只有稍后,当 get()
函数完成时,它才会调用闭包中的代码,此时您可以追加到 locations
。
我建议您阅读有关 Swift 中的闭包和异步调用的更多信息。
关于ios - 值只能在 API 调用中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42126197/