Created
October 25, 2016 03:13
-
-
Save eneko/20850fa6e3afd96d467c4f890ca3b53c to your computer and use it in GitHub Desktop.
Basic cache, failing on Ubuntu 14.04 with Swift 3.0
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 | |
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