Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 为什么不能用协议继承约束associatedtype?_Swift_Swift Protocols_Associated Types - Fatal编程技术网

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今天所支持的: