WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

What is the @State property wrapper?

Paul Hudson    @twostraws   

Updated for Xcode 14.2

SwiftUI uses the @State property wrapper to allow us to modify values inside a struct, which would normally not be allowed because structs are value types.

When we put @State before a property, we effectively move its storage out from our struct and into shared storage managed by SwiftUI. This means SwiftUI can destroy and recreate our struct whenever needed (and this can happen a lot!), without losing the state it was storing.

@State should be used with simple struct types such as String, Int, and arrays, and generally shouldn’t be shared with other views. If you want to share values across views, you should probably use @ObservedObject or @EnvironmentObject instead – both of those will ensure that all views will be refreshed when the data changes.

To re-enforce the local nature of @State properties, Apple recommends you mark them as private, like this:

@State private var username = ""

This isn’t required, but it seems like smart practice.

Tip: You can use @State to track reference types if you want, you just won’t be notified when they change. This is particularly helpful for classes that don’t conform to the ObservableObject protocol.

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.8/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.