【问题标题】:MapKit error when using AnnotatedItem in a ForEach在 ForEach 中使用 AnnotatedItem 时出现 MapKit 错误
【发布时间】:2021-06-03 21:30:44
【问题描述】:

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

 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?

【问题讨论】:

    标签: swiftui swiftui-list


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2016-05-31
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多