import UIKit
protocol CacheProtocol {
associatedtype Value
func setValue(_ value: Value?, forKey key: String)
func getValue(forKey key: String) -> Value?
func fetchValue(forKey key: String, completion: @escaping (Value?) -> Void)
}
final class Cache<T>: CacheProtocol {
private var storage: [String: T] = [:]
private let queue = DispatchQueue(label: "my.queue", attributes: .concurrent)
func setValue(_ value: T?, forKey key: String) {
queue.sync(flags: .barrier) {
storage[key] = value
}
}
func getValue(forKey key: String) -> T? {
queue.sync {
return storage[key]
}
}
func fetchValue(forKey key: String, completion: @escaping (T?) -> Void) {
queue.async {
let value = self.storage[key]
completion(value)
}
}
}