微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 ForEach 中使用 AnnotatedItem 时出现 MapKit 错误

如何解决在 ForEach 中使用 AnnotatedItem 时出现 MapKit 错误

我在 SwiftUI 中使用 MapKit,我正在尝试基于导入的 JSON 创建一个 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 时,出现以下错误

在“ForEach”上引用初始值设定项“init(_:content:)”要求“AnnotatedItem”符合“View” 静态方法“buildBlock”要求“AnnotatedItem”符合“View”

我对 Swift 相当陌生,所以我不知道如何解释错误。我将如何使 AnnotatedItem 符合 View?

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。