我知道在协议与关联值一起使用的情况下,通常需要进行类型擦除。但有时似乎有点矫枉过正。例如,在我们知道某些类将关联类型设置为 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
上的约束?有没有办法让它在没有类型擦除样板的情况下工作?