0

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.

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.