Wrapping NSCache (to limit type) is not that hard.
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))
source share