【发布时间】:2022-02-09 21:50:49
【问题描述】:
我有这个模型:
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?
}
我正在尝试遍历 Property 数组以使用 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
}
那么如何使用异步函数迭代这个数组呢?
我需要创建AsyncIterator 吗?文档对此非常困惑,对于这个简单的示例,我将如何做到这一点?
【问题讨论】:
-
所以您只想将映射
[Property]压缩到[CLLocationCoordinate2D]?我猜你展示的是 3 次尝试解决同一个问题(而不是 3 个单独的问题)? -
是的。我展示了 3 种不同的尝试以及它们给出的错误。因为我的
coordinatesvar 是异步的,因为geocodeAddressString是异步的。我想获取一个坐标数组,然后作为地图注释放置。 -
我不知道为什么一个答案被删除了,但幸运的是我在我必须出去之前设法通过屏幕抓取它并且它被删除了,因为它确实可以完成这项工作。
-
我删除了它,因为我对您的情况做了一些可能不正确的假设。您可能希望映射坐标与属性的顺序相同,对吧?使用
TaskGroup并不能保证该订单。我没有注意您正在做的事情的一般背景(添加注释),并且不认为顺序很重要。 -
啊,是的。我很快意识到我需要
Property本身的这些链接/成员来使用它的其他属性。我想我可能需要看看让Property计算init()上的坐标
标签: swift for-loop async-await concurrency