Skip to content

Commit 0978dde

Browse files
authored
Keep last non-nil value around for ForEachStore (#668)
1 parent 65f1fa0 commit 0978dde

File tree

2 files changed

+23
-22
lines changed

2 files changed

+23
-22
lines changed

Sources/ComposableArchitecture/SwiftUI/ForEachStore.swift

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,10 +101,13 @@ where Data: Collection, ID: Hashable, Content: View {
101101
// views for elements no longer in the collection.
102102
//
103103
// Feedback filed: https://gist.github.com/stephencelis/cdf85ae8dab437adc998fb0204ed9a6b
104-
let element = store.state.value[id: id]!
104+
var element = store.state.value[id: id]!
105105
return content(
106106
store.scope(
107-
state: { $0[id: id] ?? element },
107+
state: {
108+
element = $0[id: id] ?? element
109+
return element
110+
},
108111
action: { (id, $0) }
109112
)
110113
)

Sources/ComposableArchitecture/SwiftUI/IfLetStore.swift

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,15 @@ 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 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)! })))
54+
if var state = viewStore.state {
55+
return ViewBuilder.buildEither(
56+
first: ifContent(
57+
store.scope {
58+
state = $0 ?? state
59+
return state
60+
}
61+
)
62+
)
5963
} else {
6064
return ViewBuilder.buildEither(second: elseContent())
6165
}
@@ -75,11 +79,15 @@ public struct IfLetStore<State, Action, Content>: View where Content: View {
7579
) where Content == IfContent? {
7680
self.store = store
7781
self.content = { viewStore in
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)! }))
82+
if var state = viewStore.state {
83+
return ifContent(
84+
store.scope {
85+
state = $0 ?? state
86+
return state
87+
}
88+
)
89+
} else {
90+
return nil
8391
}
8492
}
8593
}
@@ -92,13 +100,3 @@ public struct IfLetStore<State, Action, Content>: View where Content: View {
92100
)
93101
}
94102
}
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)