假设你有一个PAT:
protocol PAT {
associatedtype T
func provide() -> T
}另一个协议,使用该协议作为类型约束:
protocol RegularProtocol {
func consume<P: PAT>(_ pat: P) -> P.T
}有没有办法为特定关联类型PAT实施第二个协议?例如,如果它是可能的,那就太好了,比如:
struct Consumer: RegularProtocol /*!*/ where RegularProtocol.T == () /*!*/ {
func consume<P: PAT>(_ pat: P) {
// ...
}
}我还没有找到一种方法来做任何类似的事情,我假设架构需要重新思考。不管怎么说,我是不是漏掉了什么?
任何关于处理这种情况的建议都是值得感谢的!谢谢!
发布于 2018-12-16 21:59:24
一种可能是向RegularProtocol添加一个associatedType
protocol PAT {
associatedtype T
func provide() -> T
}
protocol RegularProtocol {
associatedtype T
func consume<P: PAT>(_ pat: P) -> T where P.T == T
}
struct Consumer: RegularProtocol {
typealias T = Int
func consume<P: PAT>(_ pat: P) -> T where P.T == T {
return pat.provide() * 10
}
}请注意,没有关联类型的RegularProtocol必须接受所有PAT类型,因此您不能仅为某些类型部分实现它。
https://stackoverflow.com/questions/53802719
复制相似问题