Swift 为什么不能用协议继承约束associatedtype?
我知道,在协议与相关值一起使用的情况下,通常需要执行类型擦除。但有时这似乎有些过分。例如,当我们知道某些类将关联类型设置为Swift 为什么不能用协议继承约束associatedtype?,swift,swift-protocols,associated-types,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 gener
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())
当它在协议C中有一个约束时,为什么它仍然抱怨
func runC
上的约束?有没有一种方法可以让它在不使用类型擦除样板的情况下工作?这正是Swift今天所支持的: