I have two protocols A
and B
where B
inherits from A
.
我有两个协议A和B,其中B继承自A.
protocol A { }
protocol B: A { }
And I have a utility class which has function called add
whose parameter should conform to the protocol A
:
我有一个实用程序类,其函数名为add,其参数应符合协议A:
class Utility {
func add<T:A>(t:T.Type,param:T){
....
}
}
Then I have a test class which creates object of Utility
and calls its function add
which accepts a parameter of type B
(class object which implements B
):
然后我有一个测试类,它创建Utility的对象并调用它的函数add,它接受一个B类参数(实现B的类对象):
class Test {
var util: Utility
init() {
util = Utility()
}
func addItem(data:B){
util.add(B.self,param: data) // This line produces Cannot invoke add with argument list
} // of type (B.Protocol,param:B)
}
What am I doing wrong?
我究竟做错了什么?
1 个解决方案
#1
0
Your mistake is that you are trying to accept variable as a protocol, not the type conforming to the protocol:
你的错误是你试图接受变量作为协议,而不是符合协议的类型:
func addItem(data:B){
util.add(B.self,param: data)
}
Which is strange, because you did it right in the Utility
class. Simple fix is to do exactly the same here (using constraints):
这很奇怪,因为你在Utility类中做得很好。简单的解决方法是在这里完全相同(使用约束):
func addItem<T: B>(data: T) {
util.add(T.self, param: data)
}
#1
0
Your mistake is that you are trying to accept variable as a protocol, not the type conforming to the protocol:
你的错误是你试图接受变量作为协议,而不是符合协议的类型:
func addItem(data:B){
util.add(B.self,param: data)
}
Which is strange, because you did it right in the Utility
class. Simple fix is to do exactly the same here (using constraints):
这很奇怪,因为你在Utility类中做得很好。简单的解决方法是在这里完全相同(使用约束):
func addItem<T: B>(data: T) {
util.add(T.self, param: data)
}