Created
June 21, 2017 12:24
-
-
Save MattesGroeger/193e65b1b8465b737c343deac0536715 to your computer and use it in GitHub Desktop.
Generic in-memory cache implementation for Swift 3.0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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