I don't know how to write ForEach in Array in struct by SwiftUI.
struct Group: Identifiable,Decodable{
@DocumentID var id: String?
var name: String
var members: [[String:String]]
}
I want to display member's array by using ForEach
.
@ObservedObject var groupVM: GroupViewModel
var body: some View {
NavigationView {
List{
ScrollView{
LazyVStack(alignment: .leading){
ForEach(groupVM.group.members){ member in
groupMemberCell()
}
}
}
}
}
}
I got this error Referencing initializer 'init(_:content:)' on 'ForEach' requires that '[String : String]' conform to 'Identifiable'
.
Please tell me how to write the right way.
CodePudding user response:
This is because the value for members
(of type [[String: String]]
) does not automatically conform to Identifiable
.
It depends on your model as to how each individual member (with data [String: String]
) needs to be identified, as it's not clear from this dictionary how you would do this (a dictionary is a bunch of keys and values for each member, so how do we know which member is which based off this data?).
I'd suggest modelling each member as its own object and include a field that allows you to uniquely identify each member (such as having an id
for each member, which could be their user id in your application for example).
struct Member: Identifiable, Decodable {
var id: String
var data: [String: String]
}
Your group would then look like:
struct Group: Identifiable, Decodable {
@DocumentID var id: String?
var name: String
var members: [Member]
}