'Swift async/await in a for loop or map
I have this model:
struct ExactLocation {
var coordinates: CLLocationCoordinate2D? {
get async throws {
let geocoder = CLGeocoder()
let placemark = try await geocoder.geocodeAddressString(address)
let mark = MKPlacemark(placemark: placemark.first!)
return mark.coordinate
}
}
}
struct Property {
let exactLocation: ExactLocation?
}
I am trying to loop over an array of Property to fetch all the coordinates using Swift 5.5 async/await.
private func addAnnotations(for properties: [Property]) async {
let exactLocations = try? properties.compactMap { try $0.exactLocation?.coordinates } <-- Error: 'async' property access in a function that does not support concurrency
let annotations = await properties.compactMap { property -> MKPointAnnotation? in
if let exactLocation = property.exactLocation {
if let coordinates = try? await exactLocation.coordinates {
}
}
} <-- Error: Cannot pass function of type '(Property) async -> MKPointAnnotation?' to parameter expecting synchronous function type
properties.forEach({ property in
if let exactLocation = property.exactLocation {
if let coordinates = try? await exactLocation.coordinates {
}
}
} <-- Error: Cannot pass function of type '(Property) async -> Void' to parameter expecting synchronous function type
}
So how can I iterate over this array with an async function?
Do I need to create an AsyncIterator? The docs are quite confusing on this, how would I do this for this simple example?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
