Standard LRU Cache Implementation

I am building an application with Swift and I would like to use LRU Cache in my application. I implemented a simple LRUCache<K: Hashable, V> in Swift, but then I realized that since it already comes with the Dictionary and Array collections, I may not have a better native option.

I checked the documents and other questions and did not find anything suitable.

So my quesiton: does the Swift ship come with LRUCache? If so, how should I use it, if it is not: can I use the ObjectiveC version and still maintain my Swift type security?

+9
source share
5 answers

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)) 
+7
source

You can use HanekeSwift , it is a good general caching library written in Swift.

+2
source

There is no standard LRUCache implementation in the main Swift libraries, and there are none in frameworks such as the (Core) Foundation.

+1
source

You can use the NSOrderedSet, which combines NSArray and NSSet to run; creating an LRU cache from this is pretty trivial. Or for many purposes you can use NSCache.

0
source

Take a look at SwiftlyLRU on GitHub, this is a pure Swift implementation. Time: O (1), Space: O (1), which does not accept collisions in the internal hash table and is a single file to drag and drop into the target project.

https://github.com/justinmfischer/SwiftlyLRU

0
source

Source: https://habr.com/ru/post/975638/


All Articles