-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicCounter.swift
More file actions
132 lines (111 loc) · 3.23 KB
/
BasicCounter.swift
File metadata and controls
132 lines (111 loc) · 3.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
// BasicCounter.swift
// TCAKit Examples
//
// Created by Amit Sen on 2024-12-19.
// © 2024 Coding With Amit. All rights reserved.
import SwiftUI
import TCAKit
// MARK: - State
/// The state for our counter app
struct CounterState {
var count: Int = 0
}
// MARK: - Actions
/// All possible actions in our counter app
enum CounterAction {
case increment
case decrement
case reset
}
// MARK: - Reducer
/// The reducer handles actions and updates state
func counterReducer(
state: inout CounterState,
action: CounterAction,
dependencies: Dependencies
) -> Effect<CounterAction> {
switch action {
case .increment:
state.count += 1
case .decrement:
state.count -= 1
case .reset:
state.count = 0
}
return .none
}
// MARK: - SwiftUI View
/// The main counter view
struct CounterView: View {
@ObservedObject var store: Store<CounterState, CounterAction>
var body: some View {
WithStore(store) { store in
VStack(spacing: 20) {
// Display current count
Text("Count: \(store.state.count)")
.font(.largeTitle)
.fontWeight(.bold)
.foregroundColor(.primary)
// Action buttons
HStack(spacing: 16) {
Button("−") {
store.send(.decrement)
}
.buttonStyle(.bordered)
.controlSize(.large)
Button("Reset") {
store.send(.reset)
}
.buttonStyle(.bordered)
.controlSize(.large)
Button("+") {
store.send(.increment)
}
.buttonStyle(.bordered)
.controlSize(.large)
}
// Additional info
Text("Tap the buttons to change the count")
.font(.caption)
.foregroundColor(.secondary)
}
.padding()
}
}
}
// MARK: - App Setup
/// The main app that creates the store and displays the counter
@main
struct CounterApp: App {
// Create dependencies and store
@StateObject private var store: Store<CounterState, CounterAction>
init() {
// Initialize the store with our reducer
let dependencies = Dependencies()
self._store = StateObject(wrappedValue: Store(
initialState: CounterState(),
reducer: counterReducer,
dependencies: dependencies
))
}
var body: some Scene {
WindowGroup {
CounterView(store: store)
.navigationTitle("TCAKit Counter")
}
}
}
// MARK: - Preview
#if DEBUG
struct CounterView_Previews: PreviewProvider {
static var previews: some View {
let store = Store(
initialState: CounterState(count: 5),
reducer: counterReducer,
dependencies: Dependencies()
)
CounterView(store: store)
.previewDisplayName("Counter with count 5")
}
}
#endif