I didn't understand what is the Identifiable
protocol, and how can we used it
can you explain it for me
for example
struct MyStruct: Identifiable {
let id: String
}
Which scene it used, I found it can be used for List selection
I didn't understand what is the Identifiable
protocol, and how can we used it
can you explain it for me
for example
struct MyStruct: Identifiable {
let id: String
}
Which scene it used, I found it can be used for List selection
An Identifiable
value is any kind of data you can associate with a unique identifier.
I helps you and other Swift libs to have a standardized way to associate values in a collection without rely on a collection key or index.
For example, let’s suppose you have a list of items in the following shape:
struct Item {
let label: String
}
Considering we are interested to know which item(s) in a unordered list is/are selected for the user, what could be a best way to identify them?
The most obvious choice here would be the label
, but if label is not unique or it may vary according by the language?
In this situation, a stable and unique identifier is a great solution to solve it because whereas the value of label
, an id
is always unique.
Implement this solution is a quite simple actually:
struct Item: Identifiable {
let id: UUID
let label: String
}
The id
type can be any Hashable type, like String.
And why you need it?
Identifiable is a standard library protocol, which means it’s used whitely by many Swift libraries such as SwiftUI and 3rd party ones. So you can definitely trust on it.
In other words, Identifiable enables better and stable CRUDs without force you change the way you identify values in your dataset.