Skip to content

Commit 361e64a

Browse files
committed
Add example of using ObservableObject as view state to docs
1 parent 7e334ed commit 361e64a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Sources/SwiftCrossUI/State/ObservableObject.swift

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,32 @@
3131
/// var nested = NestedState()
3232
/// }
3333
/// ```
34+
///
35+
/// To use an observable object as part of a view's state, use the ``State`` property
36+
/// wrapper. It'll detect that it's been given an observable and will forward any
37+
/// observations published by the object's ``ObservableObject/didChange`` publisher.
38+
///
39+
/// ```swift
40+
/// class CounterState: ObservableObject {
41+
/// @Published var count = 0
42+
/// }
43+
///
44+
/// struct CounterView: View {
45+
/// @State var state = CounterState()
46+
///
47+
/// var body: some View {
48+
/// HStack {
49+
/// Button("-") {
50+
/// state.count -= 1
51+
/// }
52+
/// Text("Count: \(state.count)")
53+
/// Button("+") {
54+
/// state.count += 1
55+
/// }
56+
/// }
57+
/// }
58+
/// }
59+
/// ```
3460
public protocol ObservableObject: AnyObject {
3561
/// A publisher which publishes changes made to the object. Only publishes changes made to
3662
/// ``Published`` properties by default.

0 commit comments

Comments
 (0)