structswiftuiprotocolsidentifiable

SwiftUI - Custom Identifier with Identifiable Protocol


I'm wondering whether it's possible to override the standard identifier with a custom one.

I've a simple struct:

struct MyUserData: Identifiable {
    var userId: String
    var userFirstName: String
    var userLastName: String
}

However, the Identifiable protocol wont work without var id: ObjectIdentifier row inside the struct. At the same time, I don't want to use the "id" name. userId is also unique in my model (its a UUID). Is there a way to tell the identifiable protocol to accept "userId" instead of "id"?

Thanks!


Solution

  • You can use any Hashable as an id property required by Identifiable:

    extension MyUserData: Identifiable {
      var id: String { userId }
    }