[英]Swift protocol conformance issue with sub type of protocol
internal protocol Reducer {
associatedtype S : BaseState
associatedtype A : BaseAction
func reduce(state: S, action: A) -> S
}
internal class ReducerImpl : Reducer {
func reduce(state: MainState, action: MainAction) -> MainState { //<-- Error because MainAction is a protocol not a concrete one.
return state
}
}
internal class MainState : BaseState {}
internal protocol MainAction : BaseAction {}
internal protocol BaseState {}
internal protocol BaseAction {}
If I change MainAction
from protocol to class, the compile error disappears.如果我将
MainAction
从协议更改为 class,编译错误就会消失。
I've searching many articles to understand of this error but failed.我搜索了许多文章以了解此错误,但失败了。
Do I have to pass a concrete parameter(eg. enum, class, struct) in reduce(...)
function?我是否必须在
reduce(...)
function 中传递具体参数(例如枚举、class、结构)?
I want to make ReducerImpl
can take various action type that conform MainAction.我想让
ReducerImpl
可以采取符合MainAction 的各种动作类型。
Is there anyone who can give me explain about that error and why the Swift adopt this kind of rule.有没有人能给我解释一下这个错误以及为什么 Swift 采用这种规则。
associatedtype
has to be concrete, ie. associatedtype
必须是具体的,即。 a type and not a protocol .一个类型而不是一个协议。
What you can do is to create a narrower protocol with a generic function that accepts a MainAction
parameter:您可以做的是使用接受
MainAction
参数的通用 function 创建一个更窄的协议:
internal protocol MainReducer {
associatedtype State
func reduce<Action>(state: State, action: Action) -> State where Action: MainAction
}
internal class ReducerImpl: MainReducer {
func reduce<Action>(state: MainState, action: Action) -> MainState where Action: MainAction {
return state
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.