I'm experiencing two errors:
pending = endpoint().then { freshValue in
Causes error: "Unable to infer complex closure return type; add explicit type to disambiguate"
return Guarantee(cachedValue) as! Guarantee<t>
Causes error: "Cannot convert value of type 'T' to expected argument type 'PMKUnambiguousInitializer'"
This was working in Swift 2 (slightly edited since), however since the update to Swift 4.2 this code begins to break. I'll admit, I'm still trying to figure out all the changes from Promisekit 4 to 6.
Here's the rest of the code:
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...
}
Here you need to provide the return type from the then
block by specifying the concrete type e.g, MyClass
as below,
pending = endpoint().then { freshValue -> Guarantee<MyClass> in ...}