Skip to main content

What is the @State property wrapper?

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

What is the @State property wrapper? 관련

SwiftUI by Example

Back to Home

What is the @State property wrapper? | SwiftUI by Example

What is the @State property wrapper?

Updated for Xcode 15

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.

Tips

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.

Similar solutions…
What is the @GestureState property wrapper? | SwiftUI by Example

What is the @GestureState property wrapper?
What is the @Published property wrapper? | SwiftUI by Example

What is the @Published property wrapper?
What is the @ObservedObject property wrapper? | SwiftUI by Example

What is the @ObservedObject property wrapper?
What is the @ScaledMetric property wrapper? | SwiftUI by Example

What is the @ScaledMetric property wrapper?
What is the @Binding property wrapper? | SwiftUI by Example

What is the @Binding property wrapper?

이찬희 (MarkiiimarK)
Never Stop Learning.