我正在测试一个简单的Swift Redux实现。有人可以解释为什么打电话吗store.dispatch(.test)
原因:
Could not cast value of type '(Test.AppAction) -> ()' to '(Test.Action) -> ()'.
尽管AppAction实现了Action协议,为什么无法将AppAction强制转换为Action?
中间件接受(S, Action, (Action) -> Void)
,我将其传递给dispatch(_ action: A)
作为第三个参数。这是((Action) -> Void)
的一种,但它不能接受。
protocol State {}
protocol Action {}
typealias Reducer<S: State, A: Action> = (S, A) -> S
typealias Dispatcher = (Action) -> Void
typealias Middleware<S: State> = (S, Action, @escaping Dispatcher) -> Void
protocol Store: ObservableObject {
associatedtype S: State
associatedtype A: Action
func dispatch(action: A)
}
final class DefaultStore<S: State, A: Action>: ObservableObject {
@Published private(set) var state: S
private let reducer: Reducer<S, A>
private let middlewares: [Middleware<S>]
init(initialState: S, reducer: @escaping Reducer<S, A>, middlewares: [Middleware<S>] = []) {
self.state = initialState
self.reducer = reducer
self.middlewares = middlewares
}
func dispatch(_ action: A) {
state = reducer(state, action)
middlewares.forEach { middleware in
middleware(state, action, dispatch as! Dispatcher)
}
}
}
// START
struct AppState: State { }
enum AppAction: Action { // A test action to have smthg. to call
case test
}
let appReducer: Reducer<AppState, AppAction> = { s, a in s }
let middleware: Middleware<AppState> = { s, a, dispatch in }
var store = DefaultStore(initialState: AppState(), reducer: appReducer, middlewares: [middleware])
store.dispatch(.test)
感谢@ martin-r提供线索。在阅读@ rob-napier答案后:“但是函数参数的工作顺序相反。(字符串)->虚空是(任何)->虚空的超类型”,我将代码重写为以下代码段。这可能会节省某人处理相同问题的时间。