Skip to content

Instantly share code, notes, and snippets.

@lennet
Last active April 27, 2018 21:28
Show Gist options
  • Save lennet/a704d1add28070a8e6402798b1f9fbd2 to your computer and use it in GitHub Desktop.
Save lennet/a704d1add28070a8e6402798b1f9fbd2 to your computer and use it in GitHub Desktop.
Generic NSCache in Swift
import Foundation
class Cache<T: AnyObject>: NSCache {
subscript(key: AnyObject) -> T? {
get {
return objectForKey(key)
}
set {
if let value = newValue {
setObject(value, forKey: key)
} else {
removeObjectForKey(key)
}
}
}
func objectForKey(key: AnyObject) -> T? {
return super.objectForKey(key) as? T
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment