使用 PromiseKit 6 在 Swift 4.2 中缓存

Caching in Swift 4.2 using PromiseKit 6

我遇到了两个错误:

pending = endpoint().then { freshValue in

导致错误:"Unable to infer complex closure return type; add explicit type to disambiguate"

return Guarantee(cachedValue) as! Guarantee<t>

导致错误:"Cannot convert value of type 'T' to expected argument type 'PMKUnambiguousInitializer'"

这在 Swift 2 中有效(此后略有编辑),但是自更新到 Swift 4.2 以来,此代码开始中断。我承认,我仍在努力找出从 Promisekit 4 到 6 的所有变化。

这是代码的其余部分:

import Foundation
import PromiseKit

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

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

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

    // If cache too old (invalid), returns nil
    func cachedOrNil(maxCacheAge: TimeInterval) -> T? {
        // maxCacheAge is maximum cache age before cache is deleted
        if NSDate().timeIntervalSince(cached.date) > maxCacheAge {
            cached.value = nil
        }
        return cached.value
    }

    // If cache nil too old (stale), makes API request
    func cachedOrFresh(maxCacheAge: TimeInterval, minCacheAge: TimeInterval) -> Guarantee<T> {
        // minCacheAge is minimum cache age before API request is made
        if let cachedValue = cachedOrNil(maxCacheAge: maxCacheAge) {
            if NSDate().timeIntervalSince(cached.date) < minCacheAge {
                return Guarantee(cachedValue) as! Guarantee<T>
            }
        }
        return fresh()
    }
    /// ... More code in file...
}

这里您需要通过指定具体类型来提供 then 块中的 return 类型,例如,MyClass,如下所示,

pending = endpoint().then { freshValue -> Guarantee<MyClass> in ...}