I'm building an application with Swift and I'd like to use an LRU Cache in my application. I've implemented a simple LRUCache<K: Hashable, V>
in Swift but then I figured that since it already ships with Dictionary and Array collections I might be missing a better native option.
I've checked the docs and other questions and couldn't find anything relevant.
So my quesiton is: Does Swift ship with an LRUCache? If it does, how do I use it, if it doesn't: Can I utilize an ObjectiveC version and still maintain my Swift type safety?
Wrapping NSCache
(for type constraint) is not so hard work.
struct LRUCache<K:AnyObject, V:AnyObject> {
private let _cache = NSCache()
var countLimit:Int {
get {
return _cache.countLimit
}
nonmutating set(countLimit) {
_cache.countLimit = countLimit
}
}
subscript(key:K!) -> V? {
get {
let obj:AnyObject? = _cache.objectForKey(key)
return obj as V?
}
nonmutating set(obj) {
if(obj == nil) {
_cache.removeObjectForKey(key)
}
else {
_cache.setObject(obj!, forKey: key)
}
}
}
}
let cache = LRUCache<NSString, NSString>()
cache.countLimit = 3
cache["key1"] = "val1"
cache["key2"] = "val2"
cache["key3"] = "val3"
cache["key4"] = "val4"
cache["key5"] = "val5"
let val3 = cache["key3"]
cache["key6"] = "val6"
println((
cache["key1"],
cache["key2"],
cache["key3"],
cache["key4"],
cache["key5"],
cache["key6"]
))
result:
(nil, nil, Optional(val3), nil, Optional(val5), Optional(val6))
You could use HanekeSwift, it's a nice generic cache library written in Swift.
There isn't a standard implementation of LRUCache in the Swift main libraries, nor is there one in frameworks like (Core)Foundation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With