Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 957
SwiftUIRookie Avatar asked Dec 21 '20 15:12

SwiftUIRookie


3 Answers

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

extension MyUserData: Identifiable {
  var id: String { userId }
}
like image 183
New Dev Avatar answered Oct 20 '22 01:10

New Dev


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
    }
}
like image 32
Andrew Avatar answered Oct 20 '22 00:10

Andrew


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
}
like image 2
ios coder Avatar answered Oct 20 '22 00:10

ios coder