JSK
JSK

Reputation: 197

Getting two different results using ForEach in SwiftUI

I have list of structs that I display in the view using a ForEach, I am trying to add to the list and when the user taps they see information for that item. Using two approaches I get two different results.

First Approach

The view updates the view when items are added perfectly, but changing the note in the Details changes values of all notes.

@Binding var person: Person

ForEach(self.person.notes) {
       note in
        DetailsCard(person: self.$person, note: notes)
}

Second Approach

The view does not update when notes are added, only when the view reappears does it show the new items. But I when the items are shown, the details view works as expected.

@Binding var person: Person

ForEach(self.person.notes.indices) { index in
     VStack {
        DetailsCard(person: self.$person, note: self.person.notes[index])
     }
}

DetailView

@Binding var person: Person
@State var note: Note
    

This should be a fairly simple task but working with SwiftUI I am confused by the two different results for similar approaches. Does anyone have any ideas on why this is occurring and how to correctly dynamically update the view and pass the values.

Upvotes: 0

Views: 169

Answers (1)

pawello2222
pawello2222

Reputation: 54426

Try using dynamic ForEach loops, ie. with an explicit id parameter:

ForEach(self.person.notes, id:\.self)
ForEach(self.person.notes.indices, id:\.self)

Note: id must conform to Hashable. If you decide to use self as an id, it will only work if your item conforms to Hashable. Otherwise you may want to use some property (or just add the conformance).

Upvotes: 1

Related Questions