使用PromiseKit 6在Swift 4.2中进行缓存

时间:2018-11-02 23:41:14

标签: swift xcode10 swift4.2 promisekit

我遇到两个错误:

pending = endpoint().then { freshValue in

导致错误:“无法推断复杂的闭包返回类型;添加显式类型来消除歧义”

return Guarantee(cachedValue) as! Guarantee<t>

导致错误:“无法将类型'T'的值转换为预期的参数类型'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...
}

1 个答案:

答案 0 :(得分:1)

在这里,您需要通过指定具体类型,例如,then,从MyClass块中提供返回类型,

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