LRU, type-safe, thread-safe memory cache class in Swift
MemoryCache is a memory cache class in swift.
let memoryCache = MemoryCache.default // or initialize
// Defining a string (or hash) key for a dog value.
let dogKey = StringKey<Dog>("dog")
// Setting a dog value in memoryCache.
memoryCache.set(dog, for: dogKey)
// Getting a cached dog value in memoryCache.
let cachedDog = try? memoryCache.value(for: dogKey)
// Removing a cached dog value in memoryCache.
memoryCache.remove(for: dogKey)
let dogKey = StringKey<Dog>("dog")
memoryCache.set(dog, for: dogKey)
let dog = try? memoryCache.value(for: dogKey)
memoryCache.remove(for: dogKey)
memoryCache.removeIfExpired(for: dogKey)
memoryCache.removeAll()
/// The maximum total cost that the memoryCache can hold before it starts evicting caches.
var totalCostLimit: Int
/// The maximum number of caches the memoryCache should hold.
var countLimit: Int
/// The total cost of values in the memoryCache.
var totalCost: Int
/// The number of values in the memoryCache.
var count: Int
/// A Boolean value indicating whether the memoryCache has no values.
var isEmpty: Bool
import MemoryCache
class SomeClass: NSObject, MemoryCacheDelegate {
let memoryCache: MemoryCache
init() {
memoryCache = MemoryCache.default
...
super.init()
memoryCache.delegate = self
}
func memoryCache(_ memoryCache: MemoryCache, willEvict cache: Any) {
// Called when an cache is about to be evicted or removed from the memoryCache.
}
}
You can specify expiration date for cache. The default expiration is .never
.
/// The expiration date is `.never`.
memoryCache.set(dog, for: dogKey, expiration: .never)
/// The expiration date is `.seconds("""10s""")`.
memoryCache.set(dog, for: dogKey, expiration: .seconds(10))
/// The expiration date is `.date("""TOMORROW""")`.
memoryCache.set(dog, for: dogKey, expiration: .date(Date().addingTimeInterval(60 * 60 * 24)))
/// Remove the cache of the specified key if it expired.
memoryCache.removeIfExpired(for: dogKey)
MemoryCache is available through CocoaPods. To install
it, simply add the following line to your Podfile:
pod 'MemoryCache'
You can integrate via Carthage, too.
Add the following line to your Cartfile
:
github "yysskk/MemoryCache"
and run carthage update
MemoryCache
is available under the MIT license. See the LICENSE file for more info.