将 self 作为参数传递给需要与 self 相同类型作为参数的协议函数

Passing self as argument to a Protocol function that wants same type as self as the argument

我正在写一个异步字典,returns 一个 Future 的值为:

我的 class 中的词典是通用的,所以 class 也是。目前,用户必须阅读文档并知道如何设置 dataCall 函数,这就是字典知道如何以

形式获取键值的方式
var dataCall: ((key: Key) -> Future<Value, MyError>)?

但这需要其他程序员知道数据调用并进行设置。 所以我写了一个协议

protocol CacheDelegate {
    typealias T: Hashable
    typealias U
    func dataCallForCacheManager(cacheManager: CacheManager<T, U>) → (key: T) → Future<Value, MyError>
}

但是,如果我尝试在 init() 中将其称为

delegate.dataCallForCacheManager(self)

我收到错误

Cannot invoke dataCallForDictionary with an argument list of type '(CacheManager)'

我也做不了 var delegate: CacheDelegate? 因为

Protocol CacheDelegate can only be used as a generic constraint because it has Self or associated type requirements.

所以我发现自己陷入困境,无法将自己作为参数传递,也无法设置委托来从该协议中获取数据调用。我错过了什么吗?我愿意做Swift 2 Voodoo。

玩具示例的内容(没有 Futures 和字典以及所有内容)如下:

import Foundation

protocol Delegate {
    typealias T: Hashable
    typealias U
    func dataCallForDictionary(dictionary: MyDictionary<T, U>) -> (T) -> (U)
}

struct MyDictionary<Key: Hashable, Value> {
    typealias T = Key
    typealias U = Value

    init<Object: Delegate>(delegate: Object) {
        dataCall = delegate.dataCallForDictionary(self)
//        self.delegate = delegate
    }

    var delegate: Delegate?

    var dataCall: ((key: Key) -> Value)?
}

以您为例,您是否考虑过这样做:

protocol Delegate {
    func dataCallForDictionary<T: Hashable, U>(dictionary: MyDictionary<T, U>) -> T -> U
}

struct MyDictionary<Key: Hashable, Value> {
    var delegate: Delegate?
    var dataCall: ((key: Key) -> Value)?

    init(delegate: Delegate) {
        self.delegate = delegate
        dataCall = delegate.dataCallForDictionary(self)
    }
}

我认为 MyDictionary 结构中的委托应该很弱。