【问题标题】:Caching in Swift 4.2 using PromiseKit 6使用 PromiseKit 6 在 Swift 4.2 中缓存
【发布时间】:2018-11-02 23:41:13
【问题描述】:

我遇到了两个错误:

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...
}

【问题讨论】:

    标签: swift xcode10 swift4.2 promisekit


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 2018-08-15
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多