为什么不能用协议继承来约束关联类型?

时间:2021-03-29 11:48:11

标签: swift swift-protocols associated-types

我知道在协议与关联值一起使用的情况下,通常需要进行类型擦除。但有时似乎有点矫枉过正。例如,在我们知道某些类将关联类型设置为 Any 的情况下,我们可以创建一个协议,使用 where 子句进行约束。就像下面的例子:

protocol A {
    associatedtype B
    
    func a(b: B)
}

protocol C: A where B == Any {}

func runC(_ c: C) { // Protocol 'C' can only be used as a generic constraint because it has Self or associated type requirements
    c.a(b: Data())
}

class CImpl: C {
    func a(b: B) {
        print(b)
    }
}

runC(CImpl())

func runC 中有一个约束时,为什么它仍然抱怨 protocol C 上的约束?有没有办法让它在没有类型擦除样板的情况下工作?

0 个答案:

没有答案
相关问题