> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/ios/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/ios/swiftui/view/state/object.md).

# state object

╱🚧 under construction

[SwiftUI](/ios/swiftui.md) ⟩ [view](/ios/swiftui/view.md) ⟩ [state](/ios/swiftui/view/state.md) ⟩ object

{% hint style="success" %}
A <mark style="color:purple;">state object</mark> is an [observable object](/ios/swiftui/view/state/observable-object/observableobject.md) that is <mark style="color:yellow;">declared</mark> and <mark style="color:yellow;">initialized</mark> as a [property](/ios/swift/type/prop.md) in a [view](/ios/swiftui/view.md), the view is called an [observer](/ios/swiftui/view/state/observable-object/observer.md) of the observable object.&#x20;
{% endhint %}

Use [@StateObject](/ios/swiftui/view/state/object/stateobject.md) to <mark style="color:yellow;">declare</mark> and <mark style="color:yellow;">initialize</mark> a <mark style="color:purple;">state object</mark> in a view.

```swift
struct ContentView: View {
    
    // ⭐️ declare & initialize a state object (an observable object)
    @StateObject var data = DataModel()

    // UI
    var body: some View { ... }
    
}
```

{% tabs %}
{% tab title="💈範例一" %}

```swift
// case 1: use the data model in a single view
// ---------------------------------------------
struct ContentView: View {
    
    // ⭐️ state object (an observable object)
    @StateObject var data = CreatureZoo()

    // UI
    var body: some View {
        List {
            ForEach(data.creatures) { creature in 
                Text(creature.name)
            }
        }
    }
    
}
```

{% endtab %}

{% tab title="👥 相關" %}

* [@StateObject](/ios/swiftui/view/state/object/stateobject.md)：<mark style="color:yellow;">declare</mark> & <mark style="color:yellow;">initialize</mark> a <mark style="color:purple;">state object</mark> in a view.
* [state value](/ios/swiftui/view/state/value.md)：[state](/ios/master/term/state.md) of a [view](/ios/swiftui/view.md), <mark style="color:yellow;">declared</mark> & <mark style="color:yellow;">initialized</mark> with [@State](/ios/swiftui/view/state/value/state.md).
  {% endtab %}
  {% endtabs %}
