BeCuriouzBeCuriouz

Learn something new every day

📱 Mobile Programming
🧱

In SwiftUI, your 'view' is thrown away dozens of times a second

💡 SwiftUI views are disposable value-type descriptions, so mutable UI state must live in SwiftUI-managed storage like @State, not in plain struct properties.

Coming from UIKit or Android, you'd expect a screen element to be a long-lived object you hold onto and mutate. SwiftUI flips this: a View is a struct, a lightweight value type that gets created, discarded, and recreated constantly. Every time state changes, SwiftUI runs your view's body again, producing a brand-new struct that describes what the UI should look like right now.

That sounds wasteful, but the struct isn't the pixels on screen — it's just a cheap description. SwiftUI compares the new description against the old one (a diff) and only touches the actual rendered elements that changed. Because structs are small and stack-allocated, spinning up thousands of them per second is fast. This is why you never store mutable UI state as a plain property: a plain var would vanish the instant the struct is recreated.

Instead, you mark state with @State. SwiftUI moves that value out of the fragile struct and into stable storage it manages behind the scenes. So even though the view struct is destroyed and rebuilt, your @State counter or toggle survives — SwiftUI reconnects it to each freshly minted struct. Understanding this one idea explains most of SwiftUI's 'weird' rules about property wrappers.

🧱 In SwiftUI, your 'view' is thrown away dozens of times a second — BeCuriouz