Not That Mysterious Mysteries of SwiftUI’s @State

Nikita Lazarev-Zubov
7 min readJun 6, 2024

SwiftUI has been around for almost five years now, and @State was among the first “magical” property wrappers we were presented with the new shiny unified UI framework for developing apps for all Apple platforms. However, apparently many still consider it magical or mysterious.

Photo by visuals on Unsplash

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 my own post that shows ways to use @State. (Spoiler alert!) Initialising @State externally is absolutely normal, and I’ll tell you how to do it properly.

The Basics

As you probably know, SwiftUI Views are value types and re-created (and therefore redrawn) 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.

--

--

Nikita Lazarev-Zubov

Swift and general programming topics, Agile software development, soft skills