Avatar
import SwiftUI //var counter: Counter = .init() struct ContentView: View { @StateObject private var state: ContentViewState = .init() // @State private var state: ContentViewState = .init() var body: some View { let _ = print("A") VStack { Text("Foo") CounterView(counter: $state.counter) // CounterView(counter: state.counter) // CounterView(counter: Binding( // get: { // counter // }, set: { newValue in // counter = newValue // } // )) } .padding() } } @MainActor final class ContentViewState: ObservableObject { @Published var counter: Counter = .init() // ... } //@MainActor @Observable //final class ContentViewState { // var counter: Counter = .init() // // nonisolated init() {} //} (edited)
1:08 PM
import SwiftUI struct CounterView: View { @Binding var counter: Counter // @Bindable var counter: Counter var body: some View { let _ = print("B") VStack { Text(counter.count.description) Button("Count up") { counter.countUp() } Button("Reset") { counter.reset() } } .padding() } }
1:08 PM
struct Counter: Sendable { private(set) var count: Int = 0 mutating func countUp() { count += 1 } mutating func reset() { count = 0 } } //final class Counter { // private(set) var count: Int = 0 // // func countUp() { // count += 1 // } // // func reset() { // count = 0 // } //} //import Observation // //@MainActor @Observable //final class Counter: Sendable { // private(set) var count: Int = 0 // // func countUp() { // count += 1 // } // // func reset() { // count = 0 // } //}