-2

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

Duke
  • 47
  • 4
  • 1
    https://developer.apple.com/documentation/swift/identifiable – jnpdx Aug 04 '23 at 03:52
  • See https://developer.apple.com/documentation/swiftui/list, which shows some of the utility of `Identifiable` with `List`. – Rob Aug 04 '23 at 08:15

1 Answers1

1

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.

Jan Cássio
  • 2,076
  • 29
  • 41