Reputation: 356
I'm sure there is some trivial answer as to what I am doing wrong, but I have been stumped trying to resolve this for the past few days and really appreciate any help as I learn swift.
I have a list of Place objects where the unique id for each object is a UUID. I want to look up an item in the list of objects but the UUID's of the items are never the same, I get different results even in the same view. I can run the same loop back to back, shown in the ListView.swift
snippet below, but get completely different UUIDs printed.
I added a print statement in the id: UUID: { return UUID }
to see how many objects get created (there should be 3 as I create 3 Places) but when the button is clicked that line is executed 27 times.
Overall, I am trying to figure out why these Place objects are getting over and over again when I expect it to only execute once and create a list of 3 objects.
//PlaceListView - Called from ContentView and loads a list of ItemViews
struct PlaceListView: View {
let places: [Place]
List {
ForEach(self.places, id: \.id) { place in
ItemView(place: place)
}
}
//ItemView.swift - Trying to print the UUIDs
struct PlaceRowView: View {
@EnvironmentObject var modelData: ModelData
var body: some View {
Button(action: {
for p in modelData.savedPlaces {
print(p.id)
}
}
}
//Place.swift - Object where the ID is a UUID
struct Place: Codable, Identifiable {
var id: UUID: {
return UUID()
}
}
// ModelData.swift - Instantiating the list of Places
final class ModelData: ObservableObject {
@Published var savedPlaces: [Place] = load("data.json")
}
//App.swift - Instantiating the modelData object
@main
struct travel_trackerApp: App {
@StateObject private var modelData = ModelData()
var body: some Scene {
WindowGroup {
ContentView().environmentObject(modelData)
}
}
}
Upvotes: 0
Views: 774
Reputation: 17844
This:
struct Place: Codable, Identifiable {
var id: UUID: {
return UUID()
}
}
creates a new UUID every time the property is accessed. Change it to read
struct Place: Codable, Identifiable {
let id = UUID()
}
so the id is assigned only once.
Upvotes: 3