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!
You can use any Hashable
as an id
property required by Identifiable
:
extension MyUserData: Identifiable {
var id: String { userId }
}
Unfortunately Identifiable requires a property called id. The easiest way to solve it is to use a computed property called id to your struct.
struct MyUserData: Identifiable {
var userId: String
var userFirstName: String
var userLastName: String
var id: String {
userId
}
}
I think you need this one:
import SwiftUI
struct MyUserData
{
var userId: String
var userFirstName: String
var userLastName: String
}
struct ContentView: View {
@State var arrayOfMyUserData: [MyUserData] = [MyUserData]()
var body: some View {
List
{
ForEach(arrayOfMyUserData, id: \.userId) { item in
Text("FirstName: " + item.userFirstName) + Text(" LastName: " + item.userLastName)
}
}
.onAppear() {
arrayOfMyUserData = [MyUserData(userId: "userId1", userFirstName: "willy", userLastName: "will"),
MyUserData(userId: "userId2", userFirstName: "bob", userLastName: "mccarthy"),
MyUserData(userId: "userId3", userFirstName: "james", userLastName: "rodriguez")
]
}
}
}
Or you can use this:
struct MyUserData
{
let userId: UUID = UUID()
var userFirstName: String
var userLastName: String
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With