【问题标题】:SwiftUI reading a Core Data entity into a []SwiftUI 将 Core Data 实体读入 []
【发布时间】:2021-01-24 19:29:27
【问题描述】:

我有一个具有“纬度”和“经度”属性的核心数据实体,我想将其数据读入 MapKit 的 MapAnnotation 的 []。我了解如何使用 ForEach 遍历实体以创建视图,如下面的示例所示,但我不明白如何将数据读入 []。

ForEach(stores.reversed()) { store in
    HStack {
        Text("\(store.name ?? "")")
        Spacer()
        Text("\(store.latitude, specifier: "%.3f"),")
        Text("\(store.longitude, specifier: "%.3f")")
    }
}

“locations”是一个包含 MapAnnotation 坐标的变量。 “stores”是一个包含获取的实体数据的变量。 “位置”是 CLLocationCoordinate2D 格式的可识别对象。

以下是我尝试过的,但显然它是错误的。如何正确遍历“商店”?

@State var locations: [Location] = [
    for store in stores {
        Location(coordinate: .init(latitude: store.latitude, longitude: store.longitude))
    }
]

【问题讨论】:

标签: core-data swiftui


【解决方案1】:

数组括号内的 for 循环什么都不做,因为它不返回任何内容。我想你要找的是.map

@State var locations: [Location] = stores.map { store in
  Location(
    coordinate: .init(
      latitude: store.latitude, 
      longitude: store.longitude
    )
  )
}

【讨论】:

  • 感谢您的回复!但是,当我尝试此操作时,我在@State 行上收到错误“无法在属性初始化程序中使用实例成员 'stores';属性初始化程序在 'self' 可用之前运行”。
  • 是的,如果 stores 是另一个 State 变量(我无法从您的问题中看出它不可见),那么您不能在这样的初始化值中使用它。您很可能希望在视图中使用 .onAppear 将位置设置为您想要的值
猜你喜欢
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 2012-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多