Reputation: 7922
At minute 33:00 of Demystify SwiftUI WWDC21 video, Raj talked about the importance of using a stable & unique identifier for the data model that will be rendered in a SwiftUI view, so using something like this is not recommended:
but something like this is a best practice:
I have regular data model structs (not persisted to disk or CoreData) that I need to render their data in SwiftUI views, how to create unique and stable IDs for those models ?
Upvotes: 0
Views: 754
Reputation: 285079
It's not clearly mentioned in the WWDC video but an unique identifier is supposed to be a constant.
struct Pet : Identifiable {
let id = UUID()
}
If the struct is being created from JSON with Decodable
just add CodingKeys
to exclude the identifier
struct Pet : Decodable, Identifiable {
let id = UUID()
let name : String
private enum CodingKeys : String, CodingKey { case name }
}
Anyway use constants whenever possible.
Upvotes: 1
Reputation: 18914
You have to use a stored property instead of computed property.
as mention in docs.swift.org
computed properties, which don’t actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.
It means when using computed properties as their value change each time you are calling them.
So use stored property like this
struct Model {
var id: UUID = UUID()
}
As the computed property is that runs code again and give you to new result.
Upvotes: 1