Skip to content

Commit

Permalink
✨ Add support for Binding using SwiftUI
Browse files Browse the repository at this point in the history
  • Loading branch information
SwiftyJunnos committed Oct 5, 2024
1 parent 1df37c7 commit 44be658
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
14 changes: 12 additions & 2 deletions Examples/Counter/Counter/Counter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ struct Counter: Dripper {
@Observable
final class State {
var counter: Int = .zero
var text = ""
}

enum Action {
Expand All @@ -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
}
}
Expand Down Expand Up @@ -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)
}
Expand Down
14 changes: 14 additions & 0 deletions Sources/Dripper/Station.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
//

import Foundation
import SwiftUI

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

Expand Down Expand Up @@ -70,3 +71,16 @@ public final class Station<State: Observable, Action> {
}
}
}

extension Station where State: AnyObject {
public func bind<Member>(_ dynamicMember: WritableKeyPath<State, Member>) -> Binding<Member> {
Binding(
get: {
self.state[keyPath: dynamicMember]
},
set: { newValue in
self.state[keyPath: dynamicMember] = newValue
}
)
}
}

0 comments on commit 44be658

Please sign in to comment.