Skip to content

Commit 44be658

Browse files
committed
✨ Add support for Binding using SwiftUI
1 parent 1df37c7 commit 44be658

2 files changed

Lines changed: 26 additions & 2 deletions

File tree

Examples/Counter/Counter/Counter.swift

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ struct Counter: Dripper {
1919
@Observable
2020
final class State {
2121
var counter: Int = .zero
22+
var text = ""
2223
}
2324

2425
enum Action {
@@ -40,13 +41,14 @@ struct Counter: Dripper {
4041
case .resetCounter:
4142
state.counter = .zero
4243
case .randomNumber:
43-
return .run { pour in
44+
return .run { _ in
4445
func randomNumber() async throws -> Int {
4546
try await Task.sleep(for: .seconds(1))
4647
return Int.random(in: 0...10)
4748
}
4849
let randomNumber = try await randomNumber()
49-
await pour(.decreaseCounter)
50+
// FIXME: Data Race
51+
// await pour(.decreaseCounter)
5052
state.counter = randomNumber
5153
}
5254
}
@@ -103,6 +105,14 @@ struct CounterView: View {
103105
.padding()
104106
.background(.regularMaterial)
105107
.clipShape(.rect(cornerRadius: 10.0))
108+
109+
TextField(text: station.bind(\.text)) {
110+
Text("Enter you name here")
111+
}
112+
.textFieldStyle(.roundedBorder)
113+
.padding()
114+
115+
Text(station.text)
106116
}
107117
.font(.headline)
108118
}

Sources/Dripper/Station.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
//
77

88
import Foundation
9+
import SwiftUI
910

1011
public typealias StationOf<D: Dripper> = Station<D.State, D.Action>
1112

@@ -70,3 +71,16 @@ public final class Station<State: Observable, Action> {
7071
}
7172
}
7273
}
74+
75+
extension Station where State: AnyObject {
76+
public func bind<Member>(_ dynamicMember: WritableKeyPath<State, Member>) -> Binding<Member> {
77+
Binding(
78+
get: {
79+
self.state[keyPath: dynamicMember]
80+
},
81+
set: { newValue in
82+
self.state[keyPath: dynamicMember] = newValue
83+
}
84+
)
85+
}
86+
}

0 commit comments

Comments
 (0)