# @Published

[SwiftUI](https://lochiwei.gitbook.io/ios/swiftui) ⟩ [view](https://lochiwei.gitbook.io/ios/swiftui/view) ⟩ [state](https://lochiwei.gitbook.io/ios/swiftui/view/state) ⟩ [observable object](https://lochiwei.gitbook.io/ios/swiftui/view/state/observable-object)  ⟩ @Published

{% hint style="success" %}
Use <mark style="color:purple;">`@Published`</mark> to declare a [published value](https://lochiwei.gitbook.io/ios/swiftui/view/state/observable-object/published-value) in an [observable object](https://lochiwei.gitbook.io/ios/swiftui/view/state/observable-object/observableobject) type.
{% endhint %}

```swift
// ⭐️ 1. declare an observable object type
class CreatureZoo : ObservableObject {

    // ⭐️ 2. declare published value(s)
    @Published var creatures = [
        Creature(name: "Gorilla", emoji: "🦍"),    // `Creature` is a custom type
        Creature(name: "Peacock", emoji: "🦚"),
    ]
    
}

// content view
struct ContentView: View {

    // ⭐️ 3. initialize an observable object
    @StateObject var data = CreatureZoo()
    
    var body: some View {
        // ⭐️ 4. access `data.creatures` in subviews
    }
}
```

{% hint style="danger" %}
The <mark style="color:purple;">`@Published`</mark> attribute is [class](https://lochiwei.gitbook.io/ios/swift/type/category/basic/class) <mark style="color:yellow;">constrained</mark>. <mark style="color:yellow;">Use it with</mark> [properties](https://lochiwei.gitbook.io/ios/swift/type/prop) <mark style="color:yellow;">of classes</mark>, <mark style="color:red;">not</mark> with <mark style="color:red;">non-class</mark> [types](https://lochiwei.gitbook.io/ios/swift/type) like <mark style="color:orange;">structures</mark>.
{% endhint %}

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

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

{% tab title="📘 手冊" %}

* [Combine](https://developer.apple.com/documentation/combine) ⟩ [Published](https://developer.apple.com/documentation/combine/published)
  {% endtab %}
  {% endtabs %}
