Avatar
// // ContentView.swift // ObservationPlayground // // Created by Yuta Koshizawa on 2023/07/22. // 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") ScrollView { VStack { Text("Sum: \(state.countSum)") ForEach(state.counters.indices, id: \.self) { i in // CounterView(counter: $state.counters[i]) CounterView(counter: state.counters[i]) Divider() } // CounterView(counter: state.counter) // CounterView(counter: Binding( // get: { // counter // }, set: { newValue in // counter = newValue // } // )) } .padding() } } } //@MainActor //final class ContentViewState: ObservableObject { // @Published var counters: [Counter] = (1...100).map { _ in Counter() } // // ... //} @MainActor @Observable final class ContentViewState { var counters: [Counter] = (1...100).map { _ in Counter() } var countSum: Int { counters.lazy.map(\.count).reduce(0, +) } nonisolated init() {} }
1:50 PM
import SwiftUI struct CounterView: View { // @Binding var counter: Counter @Bindable var counter: Counter var body: some View { let _ = print("B \(counter.count)") VStack { Text(counter.count.description) Button("Count up") { counter.countUp() } Button("Reset") { counter.reset() } Stepper("", value: $counter.count) } .padding() } }
1:50 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 { var count: Int = 0 func countUp() { count += 1 } func reset() { count = 0 } }