问题
The following code:
protocol ProtocolA {
}
protocol ProtocolB {
typealias T: ProtocolA
var value : Array<T> { get set }
}
class ProtocolC {
func method<T: ProtocolA>(value: ProtocolB<T>)
{
}
}
Yields these errors:
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>)
Can anyone explain me why this is not possible? Is this a bug or intentional?
回答1:
You cannot specialize generic protocol with <>
.
Instead, you can:
func method<B: ProtocolB where B.T: ProtocolA>(value: B) {
}
That says, method
accepts B
where B
conforms ProtocolB
and its T
conforms ProtocolA
.
And, in this case, you don't need where B.T: ProtocolA
because it's obvious.
func method<B: ProtocolB>(value: B) {
...
}
回答2:
Remove the <T>
after the B
argument in the method
definition. You don't need the <T: ProtocolA>
in the method signature, either.
protocol ProtocolA {
}
typealias T = ProtocolA
protocol ProtocolB {
var value : [T] { get set }
}
class ProtocolC {
func method(value: ProtocolB)
{
}
}
来源:https://stackoverflow.com/questions/32238469/how-can-i-use-a-protocol-with-a-typealias-as-a-func-parameter