|
Dear Team, In this video, Paul introduces us to the @Observable macro, and at 3:40 he says that @State is used in structs to 'keep the property alive' aaaanndd also watch it for changes. This 'alive' term is a bit vague for me. 'Alive' how? I thought that 'alive' meant watching changes. So what is 'alive AND watching for changes'? In what other ways is the property 'alive' exactly? I hope I'm not either missing something obvious or am being taken in by some semantics. This just feels very abstract to me right now. And, is this @State's 'property-alivening' feature the reason we cannot remove the @State property wrapper when we're using the @Observable macro? Looking forward to some clarity. Thank you! Best, Ara. |
|
Hi, When a view containing a @State is created, SwiftUI also creates the object and keeps it alive as long as the view exists. This ensures the object is not destroyed and recreated with each view update, which could lead to lost state and inefficient performance. "Advanced: SwiftUI State Management". You can also read about wrapped value: State Greetings Martin |
|
🧱 Build a Lego StructureOver the time I've been learning SwiftUI, I've come to think of a So imagine I give you a box of multicolored lego bricks 🧱with the instructions to construct five rows, each containing four bricks. Each time I hand you a box with 20 random Lego bricks, you assemble a randomly colored structure. Sweet! The previous Keep the First Row the SameBut now consider a set of instructions that tell you to save the color configuration of the first row of the previous structure then build the rest of the structure with random bricks. How do you keep the state of the first row alive between the 1000s of structures that you're building? You might consider writing the color sequence on a scrap of paper? Then when you get a new box of lego pieces, you consult the scrap of paper, assemble the first row per the In short, this is how You receive a box of Lego pieces with instructions inside on how to build a structure. But now one of the instructions says to consult the PostIt note outside the box for instructions for building just the first row. Please consider that a simple Here's a Brick ExampleHere's some sample code illustrating this concept.
Keep Coding |
SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.
Sponsor Hacking with Swift and reach the world's largest Swift community!
You need to create an account or log in to reply.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.