类型 "MyClass" 不符合协议 "Collection_Delegate"

Type "MyClass" does not conform to protocol "Collection_Delegate"

我有一个 class MyClass 实现了委托的通用函数 Collection_Delegate.

我的 classes CollectionItem 是某些特定 class 的超级classes ]es

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 的某些子class 中,我想调用每个子class 具有的委托的通用 onFetAllCompleted 函数。但是 class 实现 Collection_Delegate 协议导致编译器错误

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()
    }
}

我们开始吧。 class **MyClass* 得到错误

Type "MyClass" does not conform to protocol "Collection_Delegate"

在通用函数中我得到了错误

'U' is not convertible to 'Item'

那我做错了什么?为什么通用的东西不起作用?

我认为你的泛型函数声明有点复杂。如果我理解正确的话,你的 onFetchAllCompleted 函数采用参数 T,它是 U 的集合,而 U 是一个项目。如果这是正确的,上面的表达式可以像这样简化:onFetchAllCompleted 函数采用参数 T,它是 Items 的集合。所以你的协议和 class 应该是这样的

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()
    }
}

如果这对您有帮助,请告诉我