为某个关联类型实施 PAT
Implement PAT for a certain associated type
假设您有一个 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) {
// ...
}
}
我还没有找到一种方法来做任何类似的事情,我假设需要重新思考架构。但无论如何,有什么我错过的吗?
如有任何处理此类情况的建议,我们将不胜感激!谢谢!
一种可能性是在 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
类型,因此您不能仅针对某些类型部分实现它。
假设您有一个 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) {
// ...
}
}
我还没有找到一种方法来做任何类似的事情,我假设需要重新思考架构。但无论如何,有什么我错过的吗?
如有任何处理此类情况的建议,我们将不胜感激!谢谢!
一种可能性是在 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
类型,因此您不能仅针对某些类型部分实现它。