Predict the output
CounterView keeps its own @State count. Tap it to 5, then turn Highlight on. What does it show?
struct Screen: View {
@State private var isHighlighted = false
var body: some View {
VStack {
if isHighlighted {
CounterView().border(.yellow)
} else {
CounterView()
}
Toggle("Highlight", isOn: $isHighlighted)
}
}
}Hint 1 of 1
Are the two CounterViews the same view to SwiftUI?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: B 0, with a yellow border
Correct. The other branch is a different view identity, so its state starts fresh.
Why not the others?
- A 5, with a yellow border. That needs one view whose border changes, for example
.border(isHighlighted ? .yellow : .clear). - C 5, without a border. The highlight branch draws the border.
- D It crashes. Switching branches is legal; it just resets state.