Tuesday, March 29, 2022

Lifetime of State Properties in SwiftUI

Chris Eidhof:

However, when you have worked with @State (or @StateObject), you will notice that there might be some strange behavior. Sometimes your state disappears, especially when working with a List (or to be precise: any view that uses ForEach directly or indirectly).


List creates its subviews lazily.


The children of a List will be kept around. The lifetime of a @State’s property is directly tied to the lifetime of a view. Once a list child is created, it never goes away again, unless the list goes away itself.


It turns out that while the children of a List will be kept around (including their associated state), the bodies of those views will get destroyed. These will get recreated lazily once the view appears on screen again.

Comments RSS · Twitter

Leave a Comment