Skip to content

Instantly share code, notes, and snippets.

@stephensilber
Last active April 26, 2023 14:26
Show Gist options
  • Save stephensilber/2969227f5ee1b4a490e3bb46972a8328 to your computer and use it in GitHub Desktop.
Save stephensilber/2969227f5ee1b4a490e3bb46972a8328 to your computer and use it in GitHub Desktop.
// Simple example of the reducer where Destination is a screen that is pushed onto the UINavigationController viewControllers stack
struct AppFeature: Reducer {
enum Destination: Equatable, Identifiable {
case screenA(ScreenA.State)
case screenB(ScreenB.State)
case screenC(ScreenC.State)
var id: String {
switch self {
case let .screenA(state):
return state.id
case let .screenB(state):
return state.id
case let .screenC(state):
return state.id
}
}
}
struct State: Equatable {
var route: IdentifiedArrayOf<Destination> = .init()
}
enum Action: Equatable {
case route(_ id: String, _ destination: Destination)
}
var body: some ReducerProtocol<State, Action> {
Reduce { state, action in
switch action {
case .route:
return .none
}
}
}
}
// UINavigationController
class DestinationNavigationController: UINavigationController {
let store: StoreOf<AppFeature>
let viewStore: ViewStoreOf<AppFeature>
private var routeCancellable: AnyCancellable?
init(store: StoreOf<AppFeature>) {
self.store = store
self.viewStore = ViewStore(store, observe: { $0 })
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
routeCancellable = viewStore
.publisher
.route
.sink { (route: [AppFeature.Destination]) in
// Given the array of destinations, we need to be able to scope
// the StoreOf<AppFeature> down in to child stores. With the child stores,
// (ie. StoreOf<PlaceReducer>, StoreOf<ListReducer>), we will be expected
// to return a UIViewController for it.
// NOTE: We will only ever be pushing, popping, or setting view controllers on the stack
// so there is no need to worry about presenting view controllers, sheets, etc.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment