无法将类型“ Promise <t>”的值分配给类型“ Promise <_>?”

时间:2018-11-03 15:43:03

标签: swift promisekit

我正在尝试API请求,但是收到错误

Cannot assign value of type 'Promise<T>' to type 'Promise<_>?'

我不知道“承诺<_>在哪里?”出现。

下面是代码:在as处抛出错误!承诺'

class Cache<T> {
    private let defaultMaxCacheAge: TimeInterval
    private let defaultMinCacheAge: TimeInterval
    private let endpoint: () -> Promise<T>
    private let cached = CachedValue<T>()
    private var pending: Promise<T>?

    // Always makes API request, without regard to cache
    func fresh() -> Promise<T> {
        // Limit identical API requests to one at a time
        if pending == nil {
            pending = endpoint().then { freshValue in
                self.cached.value = freshValue
                return .value(freshValue)
            }.ensure {
                self.pending = nil
            } as! Promise<T>
        }
        return pending!
    }
    //...More code...
}

和缓存的初始化

init(defaultMaxCacheAge: TimeInterval = .OneHour, defaultMinCacheAge: TimeInterval = .OneMinute, endpoint: @escaping () -> Promise<T>) {
    self.endpoint = endpoint
    self.defaultMaxCacheAge = defaultMaxCacheAge
    self.defaultMinCacheAge = defaultMinCacheAge
}

和CachedValue

class CachedValue<T> {
    var date = NSDate.distantPast
    var value: T? { didSet { date = NSDate() as Date } }
}

1 个答案:

答案 0 :(得分:1)

您似乎对在PromiseKit(migration guide to PMK6)中使用then / map感到困惑:

  

then被馈入先前的承诺值,并要求您返回承诺。
  map被送入先前的承诺值,并且要求您返回非承诺,即。一个值。

因此,您应该将then更改为map以返回T,而不是Promise<T>结束:

pending = endpoint()
    .map { freshValue in
        self.cached.value = freshValue
        return freshValue
    }.ensure {
        self.pending = nil
    }