# data model

[terms](https://lochiwei.gitbook.io/ios/master/term) ⟩ data model &#x20;

{% hint style="success" %} <mark style="color:yellow;">To share the same data between multiple</mark> [views](https://lochiwei.gitbook.io/ios/swiftui/view), you need a single [source of truth](https://lochiwei.gitbook.io/ios/master/term/source-of-truth) that is [separate](https://lochiwei.gitbook.io/ios/master/term/data-separation) <mark style="color:yellow;">from the views</mark>. This is the <mark style="color:purple;">data model</mark>, and you can share it with any views that need access to the data.
{% endhint %}

* Your [user interface](https://lochiwei.gitbook.io/ios/master/term/user-interface) may <mark style="color:yellow;">display</mark> data from the <mark style="color:purple;">data model</mark>, and may [interact](https://lochiwei.gitbook.io/ios/master/term/user-interaction) with it to <mark style="color:yellow;">modify</mark> the data.&#x20;
* A common way to construct a <mark style="color:purple;">data model</mark> for a SwiftUI [app](https://lochiwei.gitbook.io/ios/swiftui/app) is to use an [observable object](https://lochiwei.gitbook.io/ios/swiftui/view/state/observable-object/observableobject). an [observable object](https://lochiwei.gitbook.io/ios/swiftui/view/state/observable-object/observableobject) is an object (<mark style="color:orange;">reference type</mark>) that <mark style="color:yellow;">multiple views can observe</mark>.

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

* [stateobject](https://lochiwei.gitbook.io/ios/swiftui/view/state/object/stateobject "mention")
* [observableobject](https://lochiwei.gitbook.io/ios/swiftui/view/state/observable-object/observableobject "mention")
* [state](https://lochiwei.gitbook.io/ios/swiftui/view/state "mention")
  {% endtab %}
  {% endtabs %}

```swift
import SwiftUI

// ⭐️ 1. define an observable object
class CreatureZoo : ObservableObject {
    // ⭐️ 2. publish its properties
    @Published var creatures = [
        Creature(name: "Gorilla", emoji: "🦍"),
        Creature(name: "Peacock", emoji: "🦚"),
    ]
}

struct Creature : Identifiable { ... }
```
