以下代码:
protocol ProtocolA {
}
protocol ProtocolB {
typealias T: ProtocolA
var value : Array<T> { get set }
}
class ProtocolC {
func method<T: ProtocolA>(value: ProtocolB<T>)
{
}
}
产生这些错误:
error: cannot specialize non-generic type 'ProtocolB'
func method<T: ProtocolA>(value: ProtocolB<T>)
error: generic parameter 'T' is not used in function signature
func method<T: ProtocolA>(value: ProtocolB<T>)
error: protocol 'ProtocolB' can only be used as a generic constraint because it has Self or associated type requirements
func method<T: ProtocolA>(value: ProtocolB<T>)
谁能解释一下为什么这是不可能的?这是错误还是故意的?
最佳答案
您不能使用 <>
专门化通用协议(protocol) .
相反,您可以:
func method<B: ProtocolB where B.T: ProtocolA>(value: B) {
}
也就是说,method
接受 B
其中 B
符合 ProtocolB
和它的T
符合 ProtocolA
.
而且,在这种情况下,您不需要 where B.T: ProtocolA
因为这很明显。
func method<B: ProtocolB>(value: B) {
...
}
关于swift - 如何使用带有类型别名的协议(protocol)作为函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32238469/