Skip to content

Resolve binding key path crash #1784

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 32 additions & 14 deletions Sources/ComposableArchitecture/ViewStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -466,8 +466,11 @@ public final class ViewStore<ViewState, ViewAction>: ObservableObject {
get: @escaping (ViewState) -> Value,
send valueToAction: @escaping (Value) -> ViewAction
) -> Binding<Value> {
ObservedObject(wrappedValue: self)
.projectedValue[get: .init(rawValue: get), send: .init(rawValue: valueToAction)]
@ObservedState var val = get(self.state)
return .init(
get: { [$val] in $val.wrappedValue },
set: { [weak self] in self?.send(valueToAction($0)) }
)
}

/// Derives a binding from the store that prevents direct writes to state and instead sends
Expand Down Expand Up @@ -559,14 +562,6 @@ public final class ViewStore<ViewState, ViewAction>: ObservableObject {
public func binding(send action: ViewAction) -> Binding<ViewState> {
self.binding(send: { _ in action })
}

private subscript<Value>(
get state: HashableWrapper<(ViewState) -> Value>,
send action: HashableWrapper<(Value) -> ViewAction>
) -> Value {
get { state.rawValue(self.state) }
set { self.send(action.rawValue(newValue)) }
}
}

/// A convenience type alias for referring to a view store of a given reducer's domain.
Expand Down Expand Up @@ -750,8 +745,31 @@ public struct StorePublisher<State>: Publisher {
}
}

private struct HashableWrapper<Value>: Hashable {
let rawValue: Value
static func == (lhs: Self, rhs: Self) -> Bool { false }
func hash(into hasher: inout Hasher) {}
final private class ValueWrapper<V>: ObservableObject {
var value: V {
willSet { objectWillChange.send() }
}

init(_ value: V) {
self.value = value
}
}

@propertyWrapper private struct ObservedState<Value>: DynamicProperty {
@ObservedObject private var box: ValueWrapper<Value>

var wrappedValue: Value {
get { box.value }
nonmutating set { box.value = newValue }
}

var projectedValue: Binding<Value> {
.init(
get: { wrappedValue },
set: { wrappedValue = $0 }
)
}
init(wrappedValue value: Value) {
self._box = ObservedObject(wrappedValue: .init(value))
}
}