Skip to content

Commit 30f3027

Browse files
authored
Fix IfLetStore so that it does not replay first seen state on nil-value (#667)
1 parent 040cfa0 commit 30f3027

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

Sources/ComposableArchitecture/SwiftUI/IfLetStore.swift

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,11 @@ public struct IfLetStore<State, Action, Content>: View where Content: View {
5151
) where Content == _ConditionalContent<IfContent, ElseContent> {
5252
self.store = store
5353
self.content = { viewStore in
54-
if let state = viewStore.state {
55-
return ViewBuilder.buildEither(first: ifContent(store.scope(state: { $0 ?? state })))
54+
if viewStore.state != nil {
55+
let unwrapper = Optional<State>.lastWrappedValue
56+
// Force unwrap is safe here because first value from scope is non-nil and scoped store
57+
// is dismanteled after last nil value.
58+
return ViewBuilder.buildEither(first: ifContent(store.scope(state: { unwrapper($0)! })))
5659
} else {
5760
return ViewBuilder.buildEither(second: elseContent())
5861
}
@@ -72,8 +75,11 @@ public struct IfLetStore<State, Action, Content>: View where Content: View {
7275
) where Content == IfContent? {
7376
self.store = store
7477
self.content = { viewStore in
75-
viewStore.state.map { state in
76-
ifContent(store.scope(state: { $0 ?? state }))
78+
viewStore.state.map { _ in
79+
let unwrapper = Optional<State>.lastWrappedValue
80+
// Force unwrap is safe here because first value from scope is non-nil and scoped store
81+
// is dismanteled after last nil value.
82+
return ifContent(store.scope(state: { unwrapper($0)! }))
7783
}
7884
}
7985
}
@@ -86,3 +92,13 @@ public struct IfLetStore<State, Action, Content>: View where Content: View {
8692
)
8793
}
8894
}
95+
96+
extension Optional {
97+
static var lastWrappedValue: (Self) -> Self {
98+
var lastWrapped: Wrapped?
99+
return {
100+
lastWrapped = $0 ?? lastWrapped
101+
return lastWrapped
102+
}
103+
}
104+
}

0 commit comments

Comments
 (0)