Sitemap

Not That Mysterious Mysteries of SwiftUI’s @State

6 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 for using with SwiftUI views. However, apparently many still consider it magical or mysterious. Let’s reveal some its mysteries.

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 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.

--

--

Nikita Lazarev-Zubov
Nikita Lazarev-Zubov

Written by Nikita Lazarev-Zubov

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

No responses yet