From 44be658ae857f35c86eda6309d03afb960551a80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Junnos=20=EF=A3=BF?= Date: Sat, 5 Oct 2024 22:25:27 +0900 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Add=20support=20for=20`Binding`=20u?= =?UTF-8?q?sing=20SwiftUI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Examples/Counter/Counter/Counter.swift | 14 ++++++++++++-- Sources/Dripper/Station.swift | 14 ++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/Examples/Counter/Counter/Counter.swift b/Examples/Counter/Counter/Counter.swift index 390c831..85d066a 100644 --- a/Examples/Counter/Counter/Counter.swift +++ b/Examples/Counter/Counter/Counter.swift @@ -19,6 +19,7 @@ struct Counter: Dripper { @Observable final class State { var counter: Int = .zero + var text = "" } enum Action { @@ -40,13 +41,14 @@ struct Counter: Dripper { case .resetCounter: state.counter = .zero case .randomNumber: - return .run { pour in + return .run { _ in func randomNumber() async throws -> Int { try await Task.sleep(for: .seconds(1)) return Int.random(in: 0...10) } let randomNumber = try await randomNumber() - await pour(.decreaseCounter) + // FIXME: Data Race +// await pour(.decreaseCounter) state.counter = randomNumber } } @@ -103,6 +105,14 @@ struct CounterView: View { .padding() .background(.regularMaterial) .clipShape(.rect(cornerRadius: 10.0)) + + TextField(text: station.bind(\.text)) { + Text("Enter you name here") + } + .textFieldStyle(.roundedBorder) + .padding() + + Text(station.text) } .font(.headline) } diff --git a/Sources/Dripper/Station.swift b/Sources/Dripper/Station.swift index 33731fe..721268d 100644 --- a/Sources/Dripper/Station.swift +++ b/Sources/Dripper/Station.swift @@ -6,6 +6,7 @@ // import Foundation +import SwiftUI public typealias StationOf = Station @@ -70,3 +71,16 @@ public final class Station { } } } + +extension Station where State: AnyObject { + public func bind(_ dynamicMember: WritableKeyPath) -> Binding { + Binding( + get: { + self.state[keyPath: dynamicMember] + }, + set: { newValue in + self.state[keyPath: dynamicMember] = newValue + } + ) + } +}