protokolas 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] = [:]
func setValue(_ value: T?, forKey key: String) {
storage[key] = value
}
func getValue(forKey key: String) -> T? {
return storage[key]
}
func fetchValue(forKey key: String, completion: @escaping (T?) -> Void) {
let value = storage[key]
completion(value)
}
}
import XCTest
final class CacheTests: XCTestCase {
override func setUp() {
super.setUp()
}
func testSetAndGetValue() {
let cache = Cache<String>()
let key: String = "key"
let value: String = "value"
cache.setValue(value, forKey: key)
XCTAssertEqual(cache.getValue(forKey: key),
value)
cache.setValue(nil, forKey: key)
XCTAssertTrue(cache.getValue(forKey: key) == nil)
}
}
CacheTests.defaultTestSuite.run()