Member-only story
Not That Mysterious Mysteries of SwiftUI’s @State
SwiftUI has been around for almost five years now, and @State was among the first “magical” property wrappers we were presented with for using with SwiftUI views. However, apparently many still consider it magical or mysterious. Let’s reveal some its mysteries.
In the “iOS Dev Weekly” newsletter’s issue 663, Dave Verwer included @samwize’s piece called “Do NOT init State externally in SwiftUI.” After reading it, I was rather surprised, because in my opinion, the post didn’t “demystify” any “mysteries,” but rather created more confusion around the topic.
To clarify things a bit, I decided to write this post that shows ways to use @State. And (spoiler alert!) initialising @State externally is absolutely normal.
Not a member? Read here for free.
The Basics
As you probably know, SwiftUI Views are value types and re-created each time its internal state changes. The mutable internal state is represented by its properties decorated by special property wrappers, one of which is @State. The property wrapper adds an internal storage for the associated property value, which is independent from the enclosing View’s lifecycle and, thus, is not re-initialised, when the View is.
