Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard implementation of an LRU Cache

Tags:

ios

swift

lru

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?

like image 677
Benjamin Gruenbaum Avatar asked Sep 22 '14 09:09

Benjamin Gruenbaum


3 Answers

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))
like image 109
rintaro Avatar answered Nov 20 '22 01:11

rintaro


You could use HanekeSwift, it's a nice generic cache library written in Swift.

like image 40
UnsafePointer Avatar answered Nov 20 '22 00:11

UnsafePointer


There isn't a standard implementation of LRUCache in the Swift main libraries, nor is there one in frameworks like (Core)Foundation.

like image 27
AlBlue Avatar answered Nov 20 '22 00:11

AlBlue