Understanding State Updates

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In the previous demo, you created three buttons and updated each counter when the button was tapped. When using plain old variables, the screen didn’t show the updates.

This occurred because SwiftUI didn’t know something had changed. Thus, iOS displayed the same screen. This is an optimization. By not having to recalculate the screen layout for each frame, this saves battery life on the target device.

By using a State variable, you are informing SwiftUI of any updates. This means, when you change a state variable, SwiftUI will reassemble the UI all over again. For this reason, it is important to strategically pick your state variables.

You don’t want to set every single variable as State variable as that will force unnecessary updates.

Publishing Object Changes

Later on, you may create your own classes that are referenced in your user interfaces. When using these classes with SwiftUI, you can’t just mark them as a State property and be done. You need to configure the class to inform SwiftUI of any changes.

See forum comments
Download course materials from Github
Previous: Demo: Adding Buttons Next: Conclusion