Daily iOS
SwiftUI

View identity

In the code below, toggling isCompact wipes whatever was typed in the text field. Can you explain why using SwiftUI's concept of identity?

var body: some View {
    if isCompact {
        SearchField().padding(4)
    } else {
        SearchField().padding(16)
    }
}
How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

The two branches of if/else are structurally different positions, so they have different identities. On toggle, one view is removed and the other is created fresh, which resets the @State inside it.

Share a question