Created
July 15, 2019 19:20
-
-
Save karthiikmk/ebee71959b732fec168a6b95410d6358 to your computer and use it in GitHub Desktop.
Cache
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
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