Everyone has probably pressed a button that acted unexpectedly. Or maybe a switch that did nothing when toggled.
Usually that type of bug results from an error in state. Internally, the app is completely fine, but it failed to update the user interface.
So what is state? According to Dictionary.com, state is “the condition of a person or thing, as with respect to circumstances or attributes.”
If you’re like, “Huh?”, think of it as status (they are very close synonyms).
In iOS development specifically, state is the condition that your app is in. For example, if the user turns off Dark Mode, your app changes to the state of “Dark Mode Disabled”. If the user turns it on, your app changes to the state of “Dark Mode Enabled”.
But what’s tricky is to sync the UI’s state and the state of the app. Whenever a UISwitch is toggled, you must keep track of it in the app — and usually you also want to display something to the user to let them know that their action was received.
Keeping the UI and the app’s state in sync is essential — imagine if a button that was supposed to “back up” all messages… actually deleted all of them 😢 (Not that it has ever happened to me, thankfully)! And if the user is interrupted by a phone call, they expect to continue where they left off once they finish the call.
Synchronizing the UI with the app’s state is usually achieved by associating each UI element with a property. The property must match their associated element at all times, so that the app always knows what it’s displaying to the user.
I sometimes like to think of state as a mirror of the UI — it describes what is shown, and you can use it to recreate the UI if the user comes back after a break.
Although most properties that hold state are linked to the UI, they don’t have to be. You can have a property that stores internal information that doesn’t get displayed — for example, the user’s current login status:
But eventually, you’ll probably use the property to change the UI — for example, kick the user out once their session has expired.
If you’re using SwiftUI, state becomes much less of a problem (it’s taken care of automatically). But it’s always worth getting to know state — you’ll probably come across and need to use it some day.
That’s it! I hope this article helped you out!