Skip to content

Instantly share code, notes, and snippets.

@karthikAdaptavant
Created July 15, 2019 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karthikAdaptavant/ebee71959b732fec168a6b95410d6358 to your computer and use it in GitHub Desktop.
Save karthikAdaptavant/ebee71959b732fec168a6b95410d6358 to your computer and use it in GitHub Desktop.
Cache
import Foundation
public struct Cache<ValueType> {
typealias KeyType = String
private class Box<T>: NSObject {
let value: T
init(_ value: T) {
self.value = value
super.init()
}
}
private let cache = NSCache<NSString, Box<ValueType>>()
public func object(forKey key: KeyType) -> ValueType? {
return cache.object(forKey: key as NSString)?.value
}
public func setObject(_ obj: ValueType, forKey key: KeyType) {
cache.setObject(Box(obj), forKey: key as NSString)
}
public func removeObject(forKey key: KeyType) {
cache.removeObject(forKey: key as NSString)
}
public func removeAllObjects() {
cache.removeAllObjects()
}
}
let myCache = Cache<Bool>()
myCache.setObject(true, forKey: "foo")
myCache.object(forKey: "foo")
myCache.removeObject(forKey: "foo")
myCache.object(forKey: "foo")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment