How do I implement a LRU cache in Swift?

Implementing an LRU (Least Recently Used) cache in Swift is a great way to optimize memory usage for applications that need to store a limited amount of data in memory. Below is an example demonstrating how to create an LRU cache in Swift.

class LRUCache { private var cache: [Int: Int] private var order: [Int] private let capacity: Int init(capacity: Int) { self.capacity = capacity self.cache = [:] self.order = [] } func get(_ key: Int) -> Int { guard let value = cache[key] else { return -1 } // Move key to the front to mark it as recently used order.removeAll { $0 == key } order.insert(key, at: 0) return value } func put(_ key: Int, _ value: Int) { if cache.keys.contains(key) { cache[key] = value // Move key to the front to mark it as recently used order.removeAll { $0 == key } } else { if cache.count >= capacity { // Remove the least recently used key if let lruKey = order.last { cache.removeValue(forKey: lruKey) order.removeLast() } } cache[key] = value } order.insert(key, at: 0) } }

LRU Cache Swift Memory Management Caching Algorithm