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

问题描述

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...