我想了解for循环中包含完成处理程序方法的行为。
请参阅以下示例,其中我尝试获取2个地址的纬度/经度坐标。
PHAssetResourceRequestOptions
输出就像这样
let addressArray = ["1 Infinite Loop, Cupertino", "809, Harvard Ave, Sunnyvale, CA - 94087"]
var coordinatesArray = [CLLocationCoordinate2D]()
for i in 0 ..< addressArray.count {
print(i)
let address = addressArray[i]
geocoder.geocodeAddressString(address, completionHandler: {(placemarks, error) -> Void in
print("Address = \(address)");
if let placemark = placemarks?.first {
let coordinate = placemark.location?.coordinate
self.coordinatesArray.append(coordinate!)
}
})
}
// Do something here after that that
我想知道为什么代码中没有打印其他地址。第二个for循环没有调用geocodeAddressString方法。假设在for循环结束后应用程序执行没有结束,我做了很多其他事情。
答案 0 :(得分:1)
coordinates[index]
将对应addressArray[index]
class Test {
let geocoder = CLGeocoder()
//Better use a dictionary instead of an array
var coordinates = [Int: CLLocationCoordinate2D]()
func f1() {
for i in 0 ..< addressArray.count {
print(i)
let address = addressArray[i]
geocoder.geocodeAddressString(address) {placemarks, error in
print("Address = \(address)");
if let placemark = placemarks?.first {
let coordinate = placemark.location?.coordinate
self.coordinates[i] = coordinate
}
}
}
}
}