首页 > 解决方案 > 在 ForEach 中使用 AnnotatedItem 时出现 MapKit 错误

问题描述

我在 SwiftUI 中使用 MapKit,我正在尝试AnnotatedItem根据导入的 JSON 创建一个 s 数组。

 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,我收到以下错误:

在 'ForEach' 上引用初始化程序 'init(_:content:)' 要求 'AnnotatedItem' 符合 'View' 静态方法 'buildBlock' 要求 'AnnotatedItem' 符合 'View'

我对 Swift 很陌生,所以我不知道如何解释这个错误。我将如何符合AnnotatedItemView?

标签: swiftuiswiftui-list

解决方案


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))
  }
}

推荐阅读