swiftui - 在 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 很陌生,所以我不知道如何解释这个错误。我将如何符合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))
}
}
推荐阅读
- sql - 为什么我的 SQL 在使用 INSERT INTO 时会跳过某些记录?
- python - Azure Databricks 中的 Python 版本
- ibm-midrange - 如何根据RPGLE中变量内容中的某个符号对字符串变量的内容进行细分
- ghostscript - 如何在 ghospcl 中指定字体映射
- c - 如何在二维数组中正确实现插入排序算法?
- .net - 如何使用powershell从oracle表中删除数据
- reinforcement-learning - 如何检查 OpenAI 健身房环境中可用的操作?
- php - 功能测试失败时如何停止 Github Actions 步骤(使用 Codeception)
- excel - Selection.copy 然后仅使用公式插入行
- javascript - 如何在反应中设置对象状态