Demystify SwiftUI
SwiftUI look on these three things
- Identity: how SwiftUI recognizes each elements. which element is same or different across multiple updates of your app
- Lifetime: SwiftUI tracks the existence of views and data over time
- Dependencies: how SwiftUI understand when the view needs to be updated and why
Views that share the same identity /could/ represent different states of the same UI element
View that represent distinct UI elements will always have different identities.
Types of identity:
- custom or data driven ID
- structural ID: differentiate views by type and their position on the view hierarchy
Every view has an ID even if it’s not explicit identity.
Avoid AnyView
as much as possible because it will hard for SwiftUI to see structure of the code. This is because AnyView
is type-erasing wrapper type which hides the type of the view.
To avoid AnyView
we can mark the function with @ViewBuilder
and return the view type directly instead of wrapping it in AnyView
@ViewBuilder
support switch statement
Identity allows us to define stable element for different values over time. Views can have different states throughout their lifetime.
View value != view identity
@State
and @StateObject
are persistent storage associated with the view’s identity
Whenever the view identity changes, the state is replaced with the initial value. The persistance of your state is tied to the lifetime of your views.
A dependency is just an input to the view so when the dependency changes, the view is required to produce new view body.
When defining identity, we should look not just it’s stability but also its uniqueness
Related WWDC sessions:
- Data essentials in SwiftUI from WWDC 2020