所以我正在编写一个使用 Argo 的应用程序库来解析我们的 JSON。效果很好。但是,我正在尝试找到一种方法来缓存我们返回的已解析类型。它们都是作为结构实现的。我试过这样的事情:
struct CachedItem <T: Decodable where T == T.DecodedType> {
let value: T
let cachedTime: NSTimeInterval
init(value: T) {
self.value = value
cachedTime = NSDate().timeIntervalSince1970
}
func isExpired() -> Bool {
let currentTime = NSDate().timeIntervalSince1970
return ((currentTime - cachedTime) > 20.minutes)
}
}
但是,尝试创建这样的缓存:
var cache: [NSURL : CachedItem]
失败并出现错误:“对泛型类型‘CachedItem’的引用需要 <...> 中的参数”,我理解这意味着我需要做这样的事情:
var cache: [NSURL : CachedItem<Item>]
有什么办法可以在这里得到我想要的东西吗?或者关于缓存不是基于 Objective-C 的类的泛型类型的任何其他建议。
编辑:
对于后代,这是我在 Rob 的回答后想到的 Cache
和 CacheItem
类型。
struct Cache {
private var cache: [String : CachedValue] = [:]
private let queue = dispatch_queue_create("Cache Queue", DISPATCH_QUEUE_SERIAL)
mutating func setValue(value: Any?, forType type: String) {
dispatch_sync(queue) {
guard let value = value else {
return
}
self.cache[type] = CachedValue(value: value)
}
}
func valueForType<T>(type: String) -> T? {
var result: T?
dispatch_sync(queue) {
guard let cachedValue = self.cache[type] where !cachedValue.isExpired() else {
result = .None
return
}
result = cachedValue.value as? T
}
return result
}
}
struct CachedValue {
let value: Any
private let cachedTime: NSTimeInterval
init(value: Any) {
self.value = value
cachedTime = NSDate().timeIntervalSince1970
}
func isExpired() -> Bool {
let currentTime = NSDate().timeIntervalSince1970
return ((currentTime - cachedTime) > 1.minutes)
}
}
最佳答案
基本上,关于此缓存中的类型,您只能说它们是Decodable
,这实际上并没有告诉您任何有用的信息,因为它们已经被解码了。剩下 AnyObject
。如果这真的是“缓存任何东西”,那么 [NSURL: AnyObject]
甚至 [NSURL: Any]
都是合适的。这给消费端带来了很多丑陋的东西来弄清楚它的类型,但这基本上与您用来解析 JSON(从根本上与 AnyObject
一起工作)所用的相同丑陋。
我很少建议 AnyObject
,但在这种情况下,如果您真的想要一个大缓存(而不是每种类型的缓存,如果可能的话,这会更可取),它可能是合适的。
关于swift - 存储通用类型的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31842853/