Caching Layer 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
- ✓Caching Layer runs in O(1) time and O(n) space, in Swift as in every other language.
- ✓Foundation ships NSCache, which is thread-safe and evicts under memory pressure with countLimit and totalCostLimit, but its generic parameters are constrained to AnyObject, so Swift structs must be boxed to enter it, and it has no concept of time.
- ✓Write the Task into the dictionary on the same synchronous run as the lookup that missed, before any await; that ordering is the review comment.
- ✓The Swift trap: An actor is not a mutex. Every await inside an actor method is a suspension point, and while suspended the actor admits other calls, so the obvious body of check the dictionary, await the load, write the dictionary is not atomic.
- ✓Handing out a cached [Float] is a retain, not a copy: copy-on-write shares the buffer until somebody mutates.
What Caching Layer actually is
Caching Layer in Swift: what you actually reach for
Swift implementation
import Foundation
struct Peaks: Sendable { let samples: [Float] }
/// An actor serialises access but does NOT make a method atomic: every await is a
/// re-entrancy point, so the dedup handle must be installed before the first one.
actor PeakCache {
private enum Slot { case peaks(Peaks), absent }
private var stored: [String: (slot: Slot, expires: ContinuousClock.Instant)] = [:]
private var loading: [String: Task<Peaks?, Error>] = [:]
private let ttl = Duration.seconds(600), negativeTTL = Duration.seconds(20)
func peaks(for assetID: String) async throws -> Peaks? {
if let e = stored[assetID], e.expires > ContinuousClock.now {
if case .peaks(let p) = e.slot { return p }
return nil
}
// Install the Task BEFORE the first suspension: between an await and its
// resumption the actor admits other calls, and they would decode again.
let task = loading[assetID] ?? Task { try await self.decode(assetID) }
loading[assetID] = task
defer { loading[assetID] = nil }
return try await task.value
}
private func decode(_ assetID: String) async throws -> Peaks? {
let peaks = try await AudioSource.peaks(assetID)
let base = peaks == nil ? negativeTTL : ttl
stored[assetID] = (peaks.map(Slot.peaks) ?? .absent,
ContinuousClock.now.advanced(by: jitter(base)))
return peaks
}
/// +/-15%: identical TTLs give you one synchronised expiry wave per interval.
private func jitter(_ base: Duration) -> Duration {
let comps = base.components
let scaled = Double(comps.seconds) * Double.random(in: 0.85...1.15)
return .milliseconds(Int(scaled * 1000))
}
}
enum AudioSource {
static func peaks(_ id: String) async throws -> Peaks? {
id.hasPrefix("asset-") ? Peaks(samples: [0.1, 0.9]) : nil
}
}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 Caching Layer?
Foundation ships NSCache, which is thread-safe and evicts under memory pressure with countLimit and totalCostLimit, but its generic parameters are constrained to AnyObject, so Swift structs must be boxed to enter it, and it has no concept of time. URLCache covers HTTP responses specifically and honours the origin's cache headers. For value types the modern shape is an actor wrapping a Dictionary, with ContinuousClock and Duration for deadlines, Duration.components when you need the raw seconds, and Task<Success, Failure> handles serving as the de-duplication tokens.
What is the most common Swift mistake when implementing Caching Layer?
An actor is not a mutex. Every await inside an actor method is a suspension point, and while suspended the actor admits other calls, so the obvious body of check the dictionary, await the load, write the dictionary is not atomic. Measured: eight concurrent callers against a naive actor produced eight decodes; eight against a version installing the Task handle before its first await produced one. Nothing warns you, because the actor did serialise every individual statement. Reentrancy is deliberate, since a non-reentrant actor would deadlock on any callback into itself.
How does Caching Layer actually perform in Swift?
Handing out a cached [Float] is a retain, not a copy: copy-on-write shares the buffer until somebody mutates. Those retains are atomic, so a hot cache of class instances pays two atomic reference-count operations per access, often the whole difference between an actor cache and a dictionary behind a lock. Each cross-actor call is a hop onto that actor's executor, so batch reads instead of looping await. Dictionary seeds its Hasher randomly per process by default, so hash values are stable within a run and carry no guarantee across runs. 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 for Replit, check its student and free-tier options 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.