write me a simple cache in swift that has a configurable capacity and is LRU
- User
write me a simple cache in swift that has a configurable capacity and is LRU
- Assistant
Sure, here is a simple implementation of a cache in Swift that has a configurable capacity and uses the LRU (least recently used) eviction strategy:
codeclass Cache<Key: Hashable, Value> { private var capacity: Int private var cache: [Key: Value] = [:] private var lru: [Key] = [] init(capacity: Int) { self.capacity = max(0, capacity) } func get(key: Key) -> Value? { guard let value = cache[key] else { return nil } // update the LRU ordering lru.removeAll { $0 == key } lru.append(key) return value } func set(key: Key, value: Value) { // update the LRU ordering lru.removeAll { $0 == key } lru.append(key) // add the new key-value pair to the cache cache[key] = value // if the cache is over capacity, remove the least recently used item if lru.count > capacity { let keyToRemove = lru.removeFirst() cache.removeValue(forKey: keyToRemove) } } }This cache implementation uses a dictionary
cacheto store the key-value pairs, and an arraylruto keep track of the LRU ordering. Thegetmethod retrieves a value from the cache, and updates the LRU ordering. Thesetmethod adds a new key-value pair to the cache and updates the LRU ordering. If the cache is over capacity after adding the new key-value pair, it removes the least recently used item from the cache.To use this cache, you can create an instance with a specific capacity and then call the
getandsetmethods as needed:codelet cache = Cache<String, String>(capacity: 10) // add some key-value pairs to the cache cache.set(key: "key1", value: "value1") cache.set(key: "key2", value: "value2") // retrieve values from the cache let value1 = cache.get(key: "key1") // returns "value1" let value2 = cache.get(key: "key2") // returns "value2" let value3 = cache.get(key: "key3") // returns nil
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.