Swift dictionary-backed LRU cache struct
Swift
import Foundation
struct LRUCache<Key: Hashable, Value> {
private let capacity: Int
private var store: [Key: Value] = [:]
private var order: [Key] = []
init(capacity: Int) { self.capacity = max(1, capacity) }
mutating func get(_ key: Key) -> Value? {
guard let value = store[key] else { return nil }
order.removeAll { $0 == key }
order.append(key)
return value
}
mutating func put(_ key: Key, _ value: Value) {
store[key] = value
order.removeAll { $0 == key }
order.append(key)
if order.count > capacity { store[order.removeFirst()] = nil }
}
}