Skip to content

Instantly share code, notes, and snippets.

@MattesGroeger
Created June 21, 2017 12:24
Show Gist options
  • Save MattesGroeger/193e65b1b8465b737c343deac0536715 to your computer and use it in GitHub Desktop.
Save MattesGroeger/193e65b1b8465b737c343deac0536715 to your computer and use it in GitHub Desktop.
Generic in-memory cache implementation for Swift 3.0
// create a chache with 60 seconds expiration time
var cache: InMemoryCache = InMemoryCache<LocalUrl>(expirationInSeconds: 60)
// data will either be returned from cache or created via callback and then returned
let data = cache.cachedData {
// do the heavy object creation here
return MyHeavyObject()
}
// invalidate the cache, next call will have to re-create the heavy object
cache.expire()
class InMemoryCache<T> {
private var expirationInSeconds: TimeInterval!
private var currentExpirationTimestamp: TimeInterval?
private var data: T?
init(expirationInSeconds: TimeInterval) {
self.expirationInSeconds = expirationInSeconds
}
func expire() {
currentExpirationTimestamp = nil
data = nil
}
func cachedData(callback: () -> T?) -> T? {
if let cacheExpirationTimestamp = currentExpirationTimestamp, cacheExpirationTimestamp > Date().timeIntervalSince1970 {
return data
} else {
data = callback()
currentExpirationTimestamp = Date().timeIntervalSince1970 + expirationInSeconds
return data
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment