Skip to content

Instantly share code, notes, and snippets.

@eneko
Created October 25, 2016 03:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eneko/20850fa6e3afd96d467c4f890ca3b53c to your computer and use it in GitHub Desktop.
Save eneko/20850fa6e3afd96d467c4f890ca3b53c to your computer and use it in GitHub Desktop.
Basic cache, failing on Ubuntu 14.04 with Swift 3.0
import Foundation
fileprivate class CachedItem<T> {
let value: T
fileprivate init(value: T) {
self.value = value
}
}
class Cache<K: Hashable, V> {
private var cache = NSCache<NSNumber, CachedItem<V>>()
func set(value: V, forKey: K) {
let key = NSNumber(value: forKey.hashValue)
let cachedItem = CachedItem(value: value)
cache.setObject(cachedItem, forKey: key)
}
func get(key: K) -> V? {
let key = NSNumber(value: key.hashValue)
guard let item = cache.object(forKey: key) else {
print("Cache MISS")
return nil
}
print("Cache HIT")
return item.value
}
}
var cache = Cache<String, String>()
func slowReq() -> String {
print("processsing...")
sleep(1)
return "hello"
}
func fetch() -> String {
if let result = cache.get(key: "test") {
return result
}
let result = slowReq()
cache.set(value: result, forKey: "test")
return result
}
for i in 1...10 {
let result = fetch()
print(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment