首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用PromiseKit 6在SWIFT4.2中缓存

使用PromiseKit 6在SWIFT4.2中缓存
EN

Stack Overflow用户
提问于 2018-11-02 23:41:13
回答 1查看 300关注 0票数 2

我遇到了两个错误:

代码语言:javascript
复制
pending = endpoint().then { freshValue in

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

代码语言:javascript
复制
return Guarantee(cachedValue) as! Guarantee<t>

导致错误:“无法将类型'T‘的值转换为预期的参数类型'PMKUnambiguousInitializer'”

这在Swift 2中是有效的(自那以后略有编辑),但是自从更新SWIFT4.2之后,这段代码就开始崩溃了。我承认,我还在努力弄清楚从Promisekit 4到6的所有变化。

下面是其余的代码:

代码语言:javascript
复制
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...
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-04 05:59:53

在这里,您需要通过指定具体类型(例如,如下所示的then类型)从MyClass块提供返回类型。

代码语言:javascript
复制
pending = endpoint().then { freshValue -> Guarantee<MyClass> in ...}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53127041

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档