我有一个类 MyClass 实现了委托(delegate) Collection_Delegate 的通用函数。
我的类 Collection 和 Item 是某些特定类的父类(super class)
protocol Collection_Delegate {
func onFetchAllCompleted<T, U where T: Collection<U>, U: Item>(collection: T, error: String?)
}
class Collection<T>: Item {
private var items: [T]
override init (communicator: CG_API_Communicator) {
items = [T]()
super.init(communicator: communicator)
}
internal func fetchAll() {
fatalError(notImplemented)
}
internal func onFetchAllCompleted(error: String?, json: JSON?) {
fatalError(notImplemented)
}
internal func appendItem(item: T) {
self.items.append(item)
}
internal func getItems() -> [T] {
return self.items
}
}
class Item {
var itemDataRaw: JSON?
func toString() -> String? {
var retval: String?
if let value: String = itemDataRaw?.rawString(encoding: NSUTF8StringEncoding) {
retval = value
} else {
retval = "Something went badly wrong"
}
return retval
}
}
现在在 Collection 的一些子类中,我想调用每个子类的委托(delegate)的通用 onFetAllCompleted 函数。但是实现Collection_Delegate协议(protocol)的类导致编译错误
class MyClass: Collection_Delegate { // Error
func onFetchAllCompleted<T, U where T: Collection<U>, U: Item>(collection: T, error: String?){
println("MyClass.onFetchAllCompleted:\(_stdlib_getTypeName(collection))") // This displays the right class name of the subclasses
let item: Item = collection.getItems()[0] //Error
let string = item.toString()
}
}
我们开始吧。类 **MyClass* 出现错误
Type "MyClass" does not conform to protocol "Collection_Delegate"
在通用函数中我得到了错误
'U' is not convertible to 'Item'
那我做错了什么?为什么通用的东西不起作用?
最佳答案
我认为你的泛型函数声明有点复杂。如果我理解正确的话,你的 onFetchAllCompleted 函数采用参数 T,它是 U 的集合,而 U 是一个项目。如果这是正确的,上面的表达式可以像这样简化:onFetchAllCompleted 函数采用参数 T,它是 Items 的集合。所以你的协议(protocol)和类应该是这样的
protocol Collection_Delegate {
func onFetchAllCompleted<T: Collection<Item>>(collection: T, error: String?)
}
class MyClass: Collection_Delegate {
func onFetchAllCompleted<T: Collection<Item>>(collection: T, error: String?){
println("MyClass.onFetchAllCompleted:\(_stdlib_getTypeName(collection))") // This displays the right class name of the subclasses
let item: Item = collection.getItems()[0] //Error
let string = item.toString()
}
}
如果这对你有帮助,请告诉我
关于ios - 类型 "MyClass"不符合协议(protocol) "Collection_Delegate",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28850448/