Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
54 views
in Technique[技术] by (71.8m points)

SwiftUI reading a Core Data entity into a []

I have a Core Data entity with the attributes "latitude" and "longitude," and I want to read its data into a [] for MapKit's MapAnnotation. I understand how to use ForEach to iterate through an entity to create a View, as seen in the sample below, but I don't understand how I read data into a [].

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

"locations" is a variable containing coordinates for MapAnnotation. "stores" is a variable containing the fetched entity data. "Location" is an identifiable for the CLLocationCoordinate2D format.

Below is what I've attempted, but clearly it is wrong. How do I iterate through "stores" correctly?

@State var locations: [Location] = [
    for store in stores {
        Location(coordinate: .init(latitude: store.latitude, longitude: store.longitude))
    }
]
question from:https://stackoverflow.com/questions/65874973/swiftui-reading-a-core-data-entity-into-a

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A for loop inside of array brackets does nothing because it doesn’t return anything. I think what you're looking for is .map

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...