List issues with dynamic content

I have encountered the following problem with a List.

The setup is as follows

@State private var allItems : [SomeItem]
@State private var selected   : SomeItem? 
// in the body
List(allItems, $selection) { theItem in …
}

where SomeItem is a struct.

When some properties of an item in allItems changes, the values that I read in theItem are not updated.

Just as if old content was cached.

I changed allItems to a computed var and everything works OK.

I read this SO thread https://stackoverflow.com/questions/74083515/swiftui-list-item-not-updated-if-model-is-wrapped-in-state but that does not give a full explanation.

So my questions:

  • Is there effectively an issue here ?
  • when is it safe to use a State var as the Content of List ?
  • Is it OK (it seems) if the properties of items do not change ?
  • It seems also OK if the list of allItems is modified (appended, reduced) without problem changing the properties of its elements.
  • How to do if needed to change both allItems (append for instance) and change the properties of some items, as computed var cannot be modified.

Hope the question is clear.

Replies

After thinking twice, the reason is probably obvious.

SomeItem has a UUID. When content of item is changed, this id does not change.

So, from the List point of view, State var allItems has not changed, hence no update to List.

But when adding an item, State var allItems does change, hence List updated.

I did not test, but I guess that changing the id of id when changing the content would trigger a List update.

Digging more…

Nothing to do with adding elements to the array…

Just to do with items publishing the var that have to trigger a List update.

In principle, this is pretty straightforward.

In practice, when the property to observe is deep inside the item hirerchy, that requires a lot Bindings, transforming struct into classes to be observable, get isues with conformance to many protocols, force some custom inits which are nightmarish when there are Bindings…

In a word, I had to give up and find some work around by redesigning the app logic in some places.

Could there be in a future SwiftUI an equivalent to Environment var to publish a property directly to the environment ?

Is it only me or a more general issue others face ?

Hi,

Thanks for sharing your code and info! so, you did find a work around? Could you you explain how you " changed allItems to a computed var" ?

Thanks!

Rob