5 concepts · 10 practice questions
A SwiftUI view is a cheap value that describes UI. What persists, its state and its place on screen, belongs to the view's identity. Identity is structural, from the view's position in the hierarchy, or explicit, from an id. The two branches of an if/else are different identities, so switching between them destroys one view along with its @State and creates the other. To change how one view looks, change a modifier's value instead of branching.
// Two identities: toggling destroys and recreates CounterView and its @State
if isHighlighted {
CounterView().background(.yellow)
} else {
CounterView()
}
// One identity: only a modifier value changes, so the state survives
CounterView()
.background(isHighlighted ? .yellow : .clear)
Sign in to read the rest and take the 10-question test.
Sign in to continue