LRU Cache Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓LRU Cache runs in O(1) time and O(n) space, in Swift as in every other language.
- ✓Swift has no LRU cache and, importantly, NSCache is not one. NSCache is thread-safe and evicts under memory pressure, but its eviction policy is deliberately unspecified, Apple documents that it may discard anything at any time.
- ✓Nodes must be a final class, because Swift structs are value types and a linked list of values would copy rather than link.
- ✓The Swift trap: Two strong references between neighbouring nodes is a retain cycle, and ARC will never collect the list, the leak is silent and grows with traffic.
- ✓Dictionary is a copy-on-write struct; held as a stored property of a class and mutated in place it never actually copies, but hand it to a function that stores it and the next write duplicates the whole table.
What LRU Cache actually is
LRU Cache in Swift: what you actually reach for
Swift implementation
final class LRUCache<Key: Hashable, Value> {
private final class Node {
let key: Key
var value: Value
weak var prev: Node? // weak breaks the retain cycle
var next: Node?
init(_ key: Key, _ value: Value) {
self.key = key
self.value = value
}
}
private var map: [Key: Node] = [:]
private var head: Node? // most recently used
private var tail: Node? // least recently used
private let capacity: Int
init(capacity: Int) {
self.capacity = capacity
map.reserveCapacity(capacity)
}
func get(_ key: Key) -> Value? {
guard let node = map[key] else { return nil }
moveToFront(node)
return node.value
}
func put(_ key: Key, _ value: Value) {
if let node = map[key] {
node.value = value
moveToFront(node)
return
}
let node = Node(key, value)
map[key] = node
insertAtFront(node)
if map.count > capacity, let lru = tail {
remove(lru)
map.removeValue(forKey: lru.key)
}
}
private func insertAtFront(_ node: Node) {
node.next = head
head?.prev = node
head = node
if tail == nil { tail = node }
}
private func remove(_ node: Node) {
node.prev?.next = node.next
node.next?.prev = node.prev
if head === node { head = node.next }
if tail === node { tail = node.prev }
node.prev = nil
node.next = nil
}
private func moveToFront(_ node: Node) {
guard head !== node else { return }
remove(node)
insertAtFront(node)
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for LRU Cache?
Swift has no LRU cache and, importantly, NSCache is not one. NSCache is thread-safe and evicts under memory pressure, but its eviction policy is deliberately unspecified, Apple documents that it may discard anything at any time. So it is a fine opportunistic cache and an unusable one whenever a miss is more expensive than a recompute. A correct LRU means Dictionary plus a linked list of final class nodes.
What is the most common Swift mistake when implementing LRU Cache?
Two strong references between neighbouring nodes is a retain cycle, and ARC will never collect the list, the leak is silent and grows with traffic. Make one direction weak (prev below). The NSCache trap is separate and just as common: its key type must be a class (AnyObject), so String and Int keys must be bridged to NSString/NSNumber, and generic value types need boxing.
How does LRU Cache actually perform in Swift?
Dictionary is a copy-on-write struct; held as a stored property of a class and mutated in place it never actually copies, but hand it to a function that stores it and the next write duplicates the whole table. Reserve capacity up front with minimumCapacity to avoid rehashing as the cache fills. ARC retain/release traffic on the node objects is the dominant cost, which is why unowned/weak choices matter for speed as well as correctness. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.