在 ForEach 中使用 AnnotatedItem 时出现 MapKit 错误
MapKit error when using AnnotatedItem in a ForEach
我在 SwiftUI 中使用 MapKit,我正在尝试根据导入的 JSON.[=17= 创建一个 AnnotatedItem
数组]
let countries = Bundle.main.decode("Countries.json")
private var pointsOfInterest = [
ForEach(countries) { country in
AnnotatedItem(name: country.display_name, coordinate: .init(latitude: country.latitude, longitude: country.longitude))
}
]
没有使用静态值的 ForEach
,它可以工作...但是当我添加 ForEach
时,出现以下错误:
Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'AnnotatedItem' conform to 'View'
Static method 'buildBlock' requires that 'AnnotatedItem' conform to 'View'
我是 Swift 的新手,所以我不知道如何正确解释错误。我如何使 AnnotatedItem
符合视图?
ForEach
用于 View
层次结构中。您可能会想到 forEach
,它可用于对数组元素执行循环,但在这种情况下您真正想要的似乎是 .map
,它允许您将一个数组转换为另一个数组:
private var pointsOfInterest : [AnnotatedItem] {
countries.map { country in
AnnotatedItem(name: country.display_name, coordinate: .init(latitude: country.latitude, longitude: country.longitude))
}
}
我在 SwiftUI 中使用 MapKit,我正在尝试根据导入的 JSON.[=17= 创建一个 AnnotatedItem
数组]
let countries = Bundle.main.decode("Countries.json")
private var pointsOfInterest = [
ForEach(countries) { country in
AnnotatedItem(name: country.display_name, coordinate: .init(latitude: country.latitude, longitude: country.longitude))
}
]
没有使用静态值的 ForEach
,它可以工作...但是当我添加 ForEach
时,出现以下错误:
Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'AnnotatedItem' conform to 'View' Static method 'buildBlock' requires that 'AnnotatedItem' conform to 'View'
我是 Swift 的新手,所以我不知道如何正确解释错误。我如何使 AnnotatedItem
符合视图?
ForEach
用于 View
层次结构中。您可能会想到 forEach
,它可用于对数组元素执行循环,但在这种情况下您真正想要的似乎是 .map
,它允许您将一个数组转换为另一个数组:
private var pointsOfInterest : [AnnotatedItem] {
countries.map { country in
AnnotatedItem(name: country.display_name, coordinate: .init(latitude: country.latitude, longitude: country.longitude))
}
}