Skip to content

Commit 73d53be

Browse files
committed
fallback and defaulting for ReadOnlyCache
1 parent 0a198a8 commit 73d53be

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

Sources/Cache.swift

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,32 @@ extension CacheProtocol {
324324

325325
}
326326

327+
extension ReadOnlyCache {
328+
329+
public func fallback(with produceValue: @escaping (Error) throws -> Value) -> ReadOnlyCache<Key, Value> {
330+
return ReadOnlyCache(cacheName: self.cacheName, retrieve: { (key, completion) in
331+
self.retrieve(forKey: key, completion: { (result) in
332+
switch result {
333+
case .failure(let error):
334+
do {
335+
let fallbackValue = try produceValue(error)
336+
completion(.success(fallbackValue))
337+
} catch let fallbackError {
338+
completion(.failure(fallbackError))
339+
}
340+
case .success(let value):
341+
completion(.success(value))
342+
}
343+
})
344+
})
345+
}
346+
347+
public func defaulting(to defaultValue: @autoclosure @escaping () -> Value) -> ReadOnlyCache<Key, Value> {
348+
return fallback(with: { _ in defaultValue() })
349+
}
350+
351+
}
352+
327353
extension CacheProtocol {
328354

329355
public func singleKey(_ key: Key) -> Cache<Void, Value> {

0 commit comments

Comments
 (0)