StateRealmObject

@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
@propertyWrapper
public struct StateRealmObject<T> : DynamicProperty where T : RealmSubscribable, T : ThreadConfined, T : Equatable

A property wrapper type that instantiates an observable object.

Create a state realm object in a SwiftUI/View, SwiftUI/App, or SwiftUI/Scene by applying the @StateRealmObject attribute to a property declaration and providing an initial value that conforms to the doc://com.apple.documentation/documentation/Combine/ObservableObject protocol:

@StateRealmObject var model = DataModel()

SwiftUI creates a new instance of the object only once for each instance of the structure that declares the object. When published properties of the observable realm object change, SwiftUI updates the parts of any view that depend on those properties. If unmanaged, the property will be read from the object itself, otherwise, it will be read from the underlying Realm. Changes to the value will update the view asynchronously:

Text(model.title) // Updates the view any time `title` changes.

You can pass the state object into a property that has the SwiftUI/ObservedRealmObject attribute.

Get a SwiftUI/Binding to one of the state object’s properties using the $ operator. Use a binding when you want to create a two-way connection to one of the object’s properties. For example, you can let a SwiftUI/Toggle control a Boolean value called isEnabled stored in the model:

Toggle("Enabled", isOn: $model.isEnabled)

This will write the modified isEnabled property to the model object’s Realm.