为特定的关联类型实施PAT

时间:2018-12-16 13:39:55

标签: swift generics swift-protocols

假设您有一个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)  {
        // ...
    }
}

我还没有找到做类似事情的方法,并且我认为需要对架构进行重新思考。但是无论如何,有什么我想念的吗?

任何有关处理此类情况的建议都将受到赞赏!谢谢!

1 个答案:

答案 0 :(得分:3)

一种可能性是在associatedType上添加RegularProtocol

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类型,因此您不能仅对某些类型部分地实现它。