繁体   English   中英

Swift 协议子类型的协议一致性问题

[英]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 {}

如果我将MainAction从协议更改为 class,编译错误就会消失。

我搜索了许多文章以了解此错误,但失败了。

我是否必须在reduce(...) function 中传递具体参数(例如枚举、class、结构)?

我想让ReducerImpl可以采取符合MainAction 的各种动作类型。

有没有人能给我解释一下这个错误以及为什么 Swift 采用这种规则。

associatedtype必须是具体的,即。 一个类型而不是一个协议

您可以做的是使用接受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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM